_wp_scrub_utf8_fallback()
云策文档标注
概述
_wp_scrub_utf8_fallback() 是 WordPress 中的一个内部函数,用于处理 UTF-8 编码字符串中的无效字节序列,将其替换为替换字符(U+FFFD)。它作为 wp_scrub_utf8() 的备用机制,确保数据在编码问题下的安全处理。
关键要点
- 函数作用:替换 UTF-8 字符串中的无效字节序列为 U+FFFD 替换字符。
- 参数:接受一个 UTF-8 编码的字符串 $bytes,可能包含无效字节。
- 返回值:返回处理后的字符串,无效部分被替换。
- 相关函数:与 wp_scrub_utf8() 和 _wp_scan_utf8() 配合使用,用于 UTF-8 编码验证和清理。
- 引入版本:WordPress 6.9.0 中首次引入。
代码示例
function _wp_scrub_utf8_fallback( string $bytes ): string {
$bytes_length = strlen( $bytes );
$next_byte_at = 0;
$was_at = 0;
$invalid_length = 0;
$scrubbed = '';
while ( $next_byte_at < $bytes_length ) {
if ( 0 === $was_at ) {
return $bytes;
}
$scrubbed .= substr( $bytes, $was_at, $next_byte_at - $was_at );
$scrubbed .= "u{FFFD}";
$next_byte_at += $invalid_length;
$was_at = $next_byte_at;
}
return $scrubbed;
}注意事项
此函数是内部备用机制,通常通过 wp_scrub_utf8() 调用,开发者应优先使用 wp_scrub_utf8() 进行 UTF-8 清理。函数处理无效字节时,可能影响字符串长度和内容,需在数据验证场景中谨慎使用。
原文内容
Fallback mechanism for replacing invalid spans of UTF-8 bytes.
Description
Example:
'Pi�a' === _wp_scrub_utf8_fallback( "PixF1a" ); // “ñ” is 0xF1 in Windows-1252.
See also
Parameters
$bytesstringrequired-
UTF-8 encoded string which might contain spans of invalid bytes.
Source
function _wp_scrub_utf8_fallback( string $bytes ): string {
$bytes_length = strlen( $bytes );
$next_byte_at = 0;
$was_at = 0;
$invalid_length = 0;
$scrubbed = '';
while ( $next_byte_at <= $bytes_length ) {
_wp_scan_utf8( $bytes, $next_byte_at, $invalid_length );
if ( $next_byte_at >= $bytes_length ) {
if ( 0 === $was_at ) {
return $bytes;
}
return $scrubbed . substr( $bytes, $was_at, $next_byte_at - $was_at - $invalid_length );
}
$scrubbed .= substr( $bytes, $was_at, $next_byte_at - $was_at );
$scrubbed .= "u{FFFD}";
$next_byte_at += $invalid_length;
$was_at = $next_byte_at;
}
return $scrubbed;
}
Changelog
| Version | Description |
|---|---|
| 6.9.0 | Introduced. |