функция since 6.9.0

_wp_scan_utf8()

Проверено на WordPress 6.9, обновлено Источник: WordPress Developer Resources.

Сигнатура

_wp_scan_utf8( string $bytes, int $at, int $invalid_length, int|null $max_bytes = null, int|null $max_code_points = null, bool|null $has_noncharacters = null ): int

Описание

Это низкоуровневый инструмент, обеспечивающий работу различных функций UTF-8.
Он сканирует строку, пока не найдёт участки некорректных байтов.
При этом он выполняет три действия:
Присваивает $at позицию после последней успешно обработанной кодовой точки.
Присваивает $invalid_length длину максимальной подчасти некорректных байтов, начиная с $at.
Возвращает количество успешно просканированных кодовых точек.
Этой информации достаточно для построения ряда полезных функций UTF-8.
Пример:
// ñ is U+F1, which in `ISO-8859-1`/`latin1`/`Windows-1252`/`cp1252` is 0xF1.
"Pi\xF1a" === $pineapple = mb_convert_encoding( "Piña", 'Windows-1252', 'UTF-8' );
$at = $invalid_length = 0;

// The first step finds the invalid 0xF1 byte.
2 === _wp_scan_utf8( $pineapple, $at, $invalid_length );
$at === 2; $invalid_length === 1;

// The second step continues to the end of the string.
1 === _wp_scan_utf8( $pineapple, $at, $invalid_length );
$at === 4; $invalid_length === 0;Внимание! Хотя передача массива опций здесь может быть удобной с точки зрения вызывающего кода, эта функция задумана как очень низкоуровневая основа для построения функциональности более высокого уровня. Ради явного учёта затрат все аргументы передаются напрямую.

Оригинал (английский)

This is a low-level tool to power various UTF-8 functionality.
It scans through a string until it finds invalid byte spans.
When it does this, it does three things:

  • Assigns $at to the position after the last successful code point.
  • Assigns $invalid_length to the length of the maximal subpart of the invalid bytes starting at $at.
  • Returns how many code points were successfully scanned.

This information is enough to build a number of useful UTF-8 functions.

Example:

// ñ is U+F1, which in `ISO-8859-1`/`latin1`/`Windows-1252`/`cp1252` is 0xF1.
"Pi\xF1a" === $pineapple = mb_convert_encoding( "Piña", 'Windows-1252', 'UTF-8' );
$at = $invalid_length = 0;

// The first step finds the invalid 0xF1 byte.
2 === _wp_scan_utf8( $pineapple, $at, $invalid_length );
$at === 2; $invalid_length === 1;

// The second step continues to the end of the string.
1 === _wp_scan_utf8( $pineapple, $at, $invalid_length );
$at === 4; $invalid_length === 0;

Note! While passing an options array here might be convenient from a calling-code standpoint, this function is intended to serve as a very low-level foundation upon which to build higher level functionality. For the sake of keeping costs explicit all arguments are passed directly.

Параметры

$bytes string обязательный
Строка в кодировке UTF-8, которая может включать участки некорректных байтов.
$at int обязательный
С какой позиции начинать сканирование.
$invalid_length int обязательный
Будет установлено в количество байтов, которые следует игнорировать после $at.
$max_bytes int|null необязательный = null
Прекратить сканирование после обработки указанного количества байтов.
$max_code_points int|null необязательный = null
Прекратить сканирование после обработки указанного количества кодовых точек.
$has_noncharacters bool|null необязательный = null
Устанавливается, чтобы указать, содержала ли просканированная строка не-символы.

Возвращаемое значение

int

Исходный код

wp-includes/compat-utf8.php:47

function _wp_scan_utf8( string $bytes, int &$at, int &$invalid_length, ?int $max_bytes = null, ?int $max_code_points = null, ?bool &$has_noncharacters = null ): int {
	$byte_length       = strlen( $bytes );
	$end               = min( $byte_length, $at + ( $max_bytes ?? PHP_INT_MAX ) );
	$invalid_length    = 0;
	$count             = 0;
	$max_count         = $max_code_points ?? PHP_INT_MAX;
	$has_noncharacters = false;

	for ( $i = $at; $i < $end && $count <= $max_count; $i++ ) {
		/*
		 * Quickly skip past US-ASCII bytes, all of which are valid UTF-8.
		 *
		 * This optimization step improves the speed from x to x
		 * depending on whether the JIT has optimized the function.
		 */
		$ascii_byte_count = strspn(
			$bytes,
			"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" .
			"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" .
			" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f",
			$i,
			$end - $i
		);

		if ( $count + $ascii_byte_count >= $max_count ) {
			$at    = $i + ( $max_count - $count );
			$count = $max_count;
			return $count;
		}

		$count += $ascii_byte_count;
		$i     += $ascii_byte_count;

		if ( $i >= $end ) {
			$at = $end;
			return $count;
		}

		/**
		 * The above fast-track handled all single-byte UTF-8 characters. What
		 * follows MUST be a multibyte sequence otherwise theres invalid UTF-8.
		 *
		 * Therefore everything past here is checking those multibyte sequences.
		 *
		 * It may look like theres a need to check against the max bytes here,
		 * but since each match of a single character returns, this functions will
		 * bail already if crossing the max-bytes threshold. This function SHALL
		 * NOT return in the middle of a multi-byte character, so if a character
		 * falls on each side of the max bytes, the entire character will be scanned.
		 *
		 * Because its possible that there are truncated characters, the use of
		 * the null-coalescing operator with "\xC0" is a convenience for skipping
		 * length checks on every continuation bytes. This works because xC0 is
		 * always invalid in a UTF-8 string, meaning that if the string has been
		 * truncated, it will find xC0 and reject as invalid UTF-8.
		 *
		 * > [The following table] lists all of the byte sequences that are well-formed
		 * > in UTF-8. A range of byte values such as A0..BF indicates that any byte
		 * > from A0 to BF (inclusive) is well-formed in that position. Any byte value
		 * > outside of the ranges listed is ill-formed.
		 *
		 * > Table 3-7. Well-Formed UTF-8 Byte Sequences
		 *  ╭─────────────────────┬────────────┬──────────────┬─────────────┬──────────────╮
		 *   Code Points          First Byte  Second Byte   Third Byte   Fourth Byte  
		 *  ├─────────────────────┼────────────┼──────────────┼─────────────┼──────────────┤
		 *   U+0000..U+F       00..F                                              
		 *   U+0080..U+FF       C2..DF      80..BF                                  
		 *   U+0800..U+FFF       E0          A0..BF        80..BF                    
		 *   U+1000..U+CFFF       E1..EC      80..BF        80..BF                    
		 *   U+D000..U+D7FF       ED          80..F        80..BF                    
		 *   U+E000..U+FFFF       EE..EF      80..BF        80..BF                    
		 *   U+10000..U+FFFF     F0          90..BF        80..BF       80..BF       
		 *   U+40000..U+FFFFF     F1..F3      80..BF        80..BF       80..BF       
		 *   U+100000..U+FFFF   F4          80..F        80..BF       80..BF       
		 *  ╰─────────────────────┴────────────┴──────────────┴─────────────┴──────────────╯
		 *
		 * @see https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G27506
		 */

		// Valid two-byte code points.
		$b1 = ord( $bytes[ $i ] );
		$b2 = ord( $bytes[ $i + 1 ] ?? "\xC0" );

		if ( $b1 >= xC2 && $b1 <= xDF && $b2 >= x80 && $b2 <= xBF ) {
			++$count;
			++$i;
			continue;
		}

		// Valid three-byte code points.
		$b3 = ord( $bytes[ $i + 2 ] ?? "\xC0" );

		if ( $b3 < x80 || $b3 > xBF ) {
			goto invalid_utf8;
		}

		if (
			( xE0 === $b1 && $b2 >= xA0 && $b2 <= xBF ) ||
			( $b1 >= xE1 && $b1 <= xEC && $b2 >= x80 && $b2 <= xBF ) ||
			( xED === $b1 && $b2 >= x80 && $b2 <= x9F ) ||
			( $b1 >= xEE && $b1 <= xEF && $b2 >= x80 && $b2 <= xBF )
		) {
			++$count;
			$i += 2;

			// Covers the range U+FDD0U+FDEF, U+FFFE, U+FFFF.
			if ( xEF === $b1 ) {
				$has_noncharacters |= (
					( xB7 === $b2 && $b3 >= x90 && $b3 <= xAF ) ||
					( xBF === $b2 && ( xBE === $b3 || xBF === $b3 ) )
				);
			}

			continue;
		}

		// Valid four-byte code points.
		$b4 = ord( $bytes[ $i + 3 ] ?? "\xC0" );

		if ( $b4 < x80 || $b4 > xBF ) {
			goto invalid_utf8;
		}

		if (
			( xF0 === $b1 && $b2 >= x90 && $b2 <= xBF ) ||
			( $b1 >= xF1 && $b1 <= xF3 && $b2 >= x80 && $b2 <= xBF ) ||
			( xF4 === $b1 && $b2 >= x80 && $b2 <= x8F )
		) {
			++$count;
			$i += 3;

			// Covers U+FFFE, U+FFFF, U+FFFE, U+FFFF, …, U+FFFE, U+FFFF.
			$has_noncharacters |= (
				( x0F === ( $b2 & x0F ) ) &&
				xBF === $b3 &&
				( xBE === $b4 || xBF === $b4 )
			);

			continue;
		}

		/**
		 * When encountering invalid byte sequences, Unicode suggests finding the
		 * maximal subpart of a text and replacing that subpart with a single
		 * replacement character.
		 *
		 * > This practice is more secure because it does not result in the
		 * > conversion consuming parts of valid sequences as though they were
		 * > invalid. It also guarantees at least one replacement character will
		 * > occur for each instance of an invalid sequence in the original text.
		 * > Furthermore, this practice can be defined consistently for better
		 * > interoperability between different implementations of conversion.
		 *
		 * @see https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-5/#G40630
		 */
		invalid_utf8:
		$at             = $i;
		$invalid_length = 1;

		// Single-byte and two-byte characters.
		if ( ( x00 === ( $b1 & x80 ) ) || ( xC0 === ( $b1 & xE0 ) ) ) {
			return $count;
		}

		$b2 = ord( $bytes[ $i + 1 ] ?? "\xC0" );
		$b3 = ord( $bytes[ $i + 2 ] ?? "\xC0" );

		// Find the maximal subpart and skip past it.
		if ( xE0 === ( $b1 & xF0 ) ) {
			// Three-byte characters.
			$b2_valid = (
				( xE0 === $b1 && $b2 >= xA0 && $b2 <= xBF ) ||
				( $b1 >= xE1 && $b1 <= xEC && $b2 >= x80 && $b2 <= xBF ) ||
				( xED === $b1 && $b2 >= x80 && $b2 <= x9F ) ||
				( $b1 >= xEE && $b1 <= xEF && $b2 >= x80 && $b2 <= xBF )
			);

			$invalid_length = min( $end - $i, $b2_valid ? 2 : 1 );
			return $count;
		} elseif ( xF0 === ( $b1 & xF8 ) ) {
			// Four-byte characters.
			$b2_valid = (
				( xF0 === $b1 && $b2 >= x90 && $b2 <= xBF ) ||
				( $b1 >= xF1 && $b1 <= xF3 && $b2 >= x80 && $b2 <= xBF ) ||
				( xF4 === $b1 && $b2 >= x80 && $b2 <= x8F )
			);

			$b3_valid = $b3 >= x80 && $b3 <= xBF;

			$invalid_length = min( $end - $i, $b2_valid ? ( $b3_valid ? 3 : 2 ) : 1 );
			return $count;
		}

		return $count;
	}

	$at = $i;
	return $count;
}

История изменений

ВерсияОписание
6.9.0 Introduced.

Что будем искать? Например,Продвижение

Этот сайт использует куки-файлы. Оставаясь на сайте, Вы соглашаетесь на их использование. Для получения дополнительной информации, пожалуйста, ознакомьтесь с политикой в отношении персональных данных.