函数文档

seems_utf8()

💡 云策文档标注

概述

seems_utf8() 函数用于检查字符串是否为 UTF-8 编码,但自 WordPress 6.9.0 起已弃用,建议使用 wp_is_valid_utf8() 替代。

关键要点

  • 函数功能:检查字符串是否符合 UTF-8 编码模型,返回布尔值。
  • 弃用状态:自 WordPress 6.9.0 起弃用,推荐使用 wp_is_valid_utf8()。
  • 注意事项:该函数检查 5-Byte 序列,但 UTF-8 最大序列长度为 4-Byte。
  • 相关函数:涉及 mbstring_binary_safe_encoding()、reset_mbstring_encoding() 和 _deprecated_function()。

代码示例

function seems_utf8( $str ) {
    _deprecated_function( __FUNCTION__, '6.9.0', 'wp_is_valid_utf8()' );

    mbstring_binary_safe_encoding();
    $length = strlen( $str );
    reset_mbstring_encoding();

    for ( $i = 0; $i < $length; $i++ ) {
        // 检查逻辑(此处省略具体实现细节)
    }
}

📄 原文内容

Checks to see if a string is utf8 encoded.

Description

NOTE: This function checks for 5-Byte sequences, UTF8 has Bytes Sequences with a maximum length of 4.

Parameters

$strstringrequired
The string to be checked.

Return

bool True if $str fits a UTF-8 model, false otherwise.

Source

function seems_utf8( $str ) {
	_deprecated_function( __FUNCTION__, '6.9.0', 'wp_is_valid_utf8()' );

	mbstring_binary_safe_encoding();
	$length = strlen( $str );
	reset_mbstring_encoding();

	for ( $i = 0; $i < $length; $i++ ) {
		$c = ord( $str[ $i ] );

		if ( $c < 0x80 ) {
			$n = 0; // 0bbbbbbb
		} elseif ( ( $c & 0xE0 ) === 0xC0 ) {
			$n = 1; // 110bbbbb
		} elseif ( ( $c & 0xF0 ) === 0xE0 ) {
			$n = 2; // 1110bbbb
		} elseif ( ( $c & 0xF8 ) === 0xF0 ) {
			$n = 3; // 11110bbb
		} elseif ( ( $c & 0xFC ) === 0xF8 ) {
			$n = 4; // 111110bb
		} elseif ( ( $c & 0xFE ) === 0xFC ) {
			$n = 5; // 1111110b
		} else {
			return false; // Does not match any model.
		}

		for ( $j = 0; $j < $n; $j++ ) { // n bytes matching 10bbbbbb follow?
			if ( ( ++$i === $length ) || ( ( ord( $str[ $i ] ) & 0xC0 ) !== 0x80 ) ) {
				return false;
			}
		}
	}

	return true;
}

Changelog

Version Description
6.9.0 Deprecated. Use wp_is_valid_utf8() instead.
1.2.1 Introduced.