mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_decode_numericentityДекодирует HTML-строку с числовой ссылкой на кодовую точку Юникода в символ

Описание

mb_decode_numericentity(string $string, array $map, ?string $encoding = null): string

Функция преобразовывает числовые ссылки на символы в строке string в символы Юникода, если ссылки входят в заданный блок кодовых точек.

Список параметров

string

Декодируемая строка (string).

map

Параметр map принимает массив, в котором указывается диапазон кодовых точек для преобразования.

encoding

Параметр encoding устанавливает кодировку символов. Функция установит для параметра значение внутренней кодировки символов, если аргумент не передали или передали значение null.

is_hex

Параметр устарел.

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

Функция возвращает преобразованную строку (string).

Ошибки

Функция выбрасывает ошибку ValueError, если значение если в параметр map передали аргумент, который не содержит список значений с типом int.

Список изменений

Версия Описание
8.4.0 Функция mb_decode_numericentity() теперь выбрасывает ошибку ValueError, если в параметр map передали аргумент, который не содержит список значений с типом int.
8.0.0 Теперь параметр encoding принимает значение null.

Примеры

Пример #1 Пример формата для установки параметра map

<?php

$convmap
= array(
int start_code1, int end_code1, int offset1, int mask1,
int start_code2, int end_code2, int offset2, int mask2,
// ........
int start_codeN, int end_codeN, int offsetN, int maskN
);
// Значениями start_codeN и end_codeN определяется диапазон кодовых точек Юникода.
// К кодовой точке исходного символа добавляется смещение offsetN и выполняется побитовая операция 'И' со значением маски maskN,
// а полученное значение затем преобразовывается в числовую ссылку на символ.

?>

Пример #2 Пример экранирования строки JavaScript-кода через параметр map

<?php

function escape_javascript_string($str)
{
$map = [
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,0,0, // 49
0,0,0,0,0,0,0,0,1,1,
1,1,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,1,0,0,0, // 99
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 149
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 199
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 249
1,1,1,1,1,1,1, // 255
];

// Кодировка символа UTF-8
$mblen = mb_strlen($str, 'UTF-8');
$utf32 = bin2hex(mb_convert_encoding($str, 'UTF-32', 'UTF-8'));

for (
$i=0, $encoded=''; $i < $mblen; $i++) {
$u = substr($utf32, $i * 8, 8);
$v = base_convert($u, 16, 10);

if (
$v < 256 && $map[$v]) {
$encoded .= '\\x' . substr($u, 6,2);
} else if (
$v == 2028) {
$encoded .= '\\u2028';
} else if (
$v == 2029) {
$encoded .= '\\u2029';
} else {
$encoded .= mb_convert_encoding(hex2bin($u), 'UTF-8', 'UTF-32');
}
}

return
$encoded;
}

// Данные для теста
$convmap = [ 0x0, 0xffff, 0, 0xffff ];
$msg = '';

for (
$i=0; $i < 1000; $i++) {
// Функцией chr() невозможно сгенерировать правильные данные в кодировке UTF-8 с кодовыми точками больше 128,
// поэтому вызывается функция mb_decode_numericentity()
$msg .= mb_decode_numericentity('&#' . $i . ';', $convmap, 'UTF-8');
}

// var_dump($msg);
var_dump(escape_javascript_string($msg));

?>

Смотрите также

  • mb_encode_numericentity() - Кодирует символ в HTML-строку с числовой ссылкой на кодовую точку Юникода

Добавить

Примечания пользователей 4 notes

up
0
abderrahmanekaddour dot aissat at gmail dot com
2 years ago
<?php

// the following documentation depending on understanding of the code source of php mbr
// first in order to optimise the work of php
// the string must contain "&" or else php won't bother trying to decode.
// for the map : int start_codeN, int end_codeN, int offsetN, int maskN
// the entity must be in the range [start_codeN, end_codeN] , if the entity is greater or less
// mb_decode_numericentity will ignore the decode process and return the $string as it is.
// in the late version of php, $map : "must have a multiple of 4 elements"

$map = [ 0x0, 0xFFFF, 0, 0];
echo
mb_decode_numericentity('&#109;', $map ); // result "m"
// if offsetN = 1 result "l" ; the more you increase the decimal the more it use OR operrand.
$map_2 = [ 0x0, 0xFFFF, 60, 0];
echo
mb_decode_numericentity('&#109;', $map_2 ); // decode ( &#49; ) result : "1"

// entity Reference to check the result : https://cs.stanford.edu/people/miles/iso8859.html#ISO

?>
up
0
donovan at conduit it
19 years ago
note that at this time it seems that mb_decode_numericentity() only works with decimal entities and not hexadecimal entities. This fact would have saved me a good hour of time in debugging.

For those who need to convert hex entities try first converting them all to decimal entities with a combination of the preg_replace() and hexdec() functions.
up
0
dev at glossword info
21 years ago
Just two great functions for daily use:

/* Converts any HTML-entities into characters */
function my_numeric2character($t)
{
$convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
return mb_decode_numericentity($t, $convmap, 'UTF-8');
}
/* Converts any characters into HTML-entities */
function my_character2numeric($t)
{
$convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
return mb_encode_numericentity($t, $convmap, 'UTF-8');
}
print my_numeric2character('&#8217; &#7936; &#226;');
print my_character2numeric(' ? ? ');
up
-2
fernandosilveira at yahoo dot com dot br
4 years ago
Be careful!
In addition to translate numeric entities to chars on specified target encoding, this function encodes every character from input string to the specified target encodin, even if the characters are outside the range defined by the conversion map.
To Top