utf8_uri_encode()
云策文档标注
概述
utf8_uri_encode() 函数用于将 Unicode 值编码为 URI 可用的格式,支持控制编码长度和 ASCII 字符处理。它是 WordPress 核心函数,常用于处理 URL 中的字符串。
关键要点
- 函数签名:utf8_uri_encode( $utf8_string, $length = 0, $encode_ascii_characters = false )
- 参数:$utf8_string(必需,要编码的字符串)、$length(必需,最大长度,默认为 0 表示无限制)、$encode_ascii_characters(可选,是否编码 ASCII 字符,默认为 false)
- 返回值:编码后的字符串,适用于 URI 使用
- 内部使用 mbstring_binary_safe_encoding() 和 reset_mbstring_encoding() 确保二进制安全编码
- 相关函数:sanitize_title_with_dashes() 和 _truncate_post_slug() 依赖此函数
- 版本历史:从 WordPress 1.5.0 引入,5.8.3 版本新增 encode_ascii_characters 参数
代码示例
// 基本用法:编码 Unicode 字符串
$encoded = utf8_uri_encode('Hello 世界', 20, false);
// 输出编码后的 URI 安全字符串
// 控制长度:限制编码后字符串的最大长度
$encoded_limited = utf8_uri_encode('测试字符串', 10, true);
// 如果超出长度,编码会提前终止注意事项
- 函数默认不编码 ASCII 字符(如字母、数字),设置 $encode_ascii_characters 为 true 可强制编码
- 长度参数 $length 为 0 时表示无限制,否则编码会在达到指定长度时停止
- 确保服务器环境支持 mbstring 扩展,函数内部依赖相关函数处理多字节字符串
- 此函数主要用于内部 URL 处理,如生成 slug 或清理标题,不建议直接用于用户输入的安全过滤
原文内容
Encodes the Unicode values to be used in the URI.
Parameters
$utf8_stringstringrequired-
String to encode.
$lengthintrequired-
Max length of the string.
$encode_ascii_charactersbooloptional-
Whether to encode ascii characters such as < " ‘
Default:
false
Source
function utf8_uri_encode( $utf8_string, $length = 0, $encode_ascii_characters = false ) {
$unicode = '';
$values = array();
$num_octets = 1;
$unicode_length = 0;
mbstring_binary_safe_encoding();
$string_length = strlen( $utf8_string );
reset_mbstring_encoding();
for ( $i = 0; $i < $string_length; $i++ ) {
$value = ord( $utf8_string[ $i ] );
if ( $value < 128 ) {
$char = chr( $value );
$encoded_char = $encode_ascii_characters ? rawurlencode( $char ) : $char;
$encoded_char_length = strlen( $encoded_char );
if ( $length && ( $unicode_length + $encoded_char_length ) > $length ) {
break;
}
$unicode .= $encoded_char;
$unicode_length += $encoded_char_length;
} else {
if ( 0 === count( $values ) ) {
if ( $value < 224 ) {
$num_octets = 2;
} elseif ( $value < 240 ) {
$num_octets = 3;
} else {
$num_octets = 4;
}
}
$values[] = $value;
if ( $length && ( $unicode_length + ( $num_octets * 3 ) ) > $length ) {
break;
}
if ( count( $values ) === $num_octets ) {
for ( $j = 0; $j < $num_octets; $j++ ) {
$unicode .= '%' . dechex( $values[ $j ] );
}
$unicode_length += $num_octets * 3;
$values = array();
$num_octets = 1;
}
}
}
return $unicode;
}