Php показать код символа

Php показать код символа

ord — Convert the first byte of a string to a value between 0 and 255

Description

Interprets the binary value of the first byte of character as an unsigned integer between 0 and 255.

If the string is in a single-byte encoding, such as ASCII, ISO-8859, or Windows 1252, this is equivalent to returning the position of a character in the character set’s mapping table. However, note that this function is not aware of any string encoding, and in particular will never identify a Unicode code point in a multi-byte encoding such as UTF-8 or UTF-16.

This function complements chr() .

Parameters

Return Values

An integer between 0 and 255.

Examples

Example #1 ord() example

Example #2 Examining the individual bytes of a UTF-8 string

declare( encoding = ‘UTF-8’ );
$str = «🐘» ;
for ( $pos = 0 ; $pos < strlen ( $str ); $pos ++ ) $byte = substr ( $str , $pos );
echo ‘Byte ‘ . $pos . ‘ of $str has value ‘ . ord ( $byte ) . PHP_EOL ;
>
?>

The above example will output:

Byte 0 of $str has value 240
Byte 1 of $str has value 159
Byte 2 of $str has value 144
Byte 3 of $str has value 152

See Also

  • chr() — Generate a single-byte string from a number
  • An » ASCII-table
  • mb_ord() — Get Unicode code point of character
  • IntlChar::ord() — Return Unicode code point value of character

User Contributed Notes 6 notes

As ord() doesn’t work with utf-8, and if you do not have access to mb_* functions, the following function will work well:
function ordutf8 ( $string , & $offset ) $code = ord ( substr ( $string , $offset , 1 ));
if ( $code >= 128 ) < //otherwise 0xxxxxxx
if ( $code < 224 ) $bytesnumber = 2 ; //110xxxxx
else if ( $code < 240 ) $bytesnumber = 3 ; //1110xxxx
else if ( $code < 248 ) $bytesnumber = 4 ; //11110xxx
$codetemp = $code — 192 — ( $bytesnumber > 2 ? 32 : 0 ) — ( $bytesnumber > 3 ? 16 : 0 );
for ( $i = 2 ; $i <= $bytesnumber ; $i ++) $offset ++;
$code2 = ord ( substr ( $string , $offset , 1 )) — 128 ; //10xxxxxx
$codetemp = $codetemp * 64 + $code2 ;
>
$code = $codetemp ;
>
$offset += 1 ;
if ( $offset >= strlen ( $string )) $offset = — 1 ;
return $code ;
>
?>
$offset is a reference, as it is not easy to split a utf-8 char-by-char. Useful to iterate on a string:
$text = «abcàê߀abc» ;
$offset = 0 ;
while ( $offset >= 0 ) echo $offset . «: » . ordutf8 ( $text , $offset ). «\n» ;
>
/* returns:
0: 97
1: 98
2: 99
3: 224
5: 234
7: 223
9: 8364
12: 97
13: 98
14: 99
*/
?>
Feel free to adapt my code to fit your needs.

Regarding character sets, and whether or not this is «ASCII». Firstly, there is no such thing as «8-bit ASCII», so if it were ASCII it would only ever return integers up to 127. 8-bit ASCII-compatible encodings include the ISO 8859 family of encodings, which map various common characters to the values from 128 to 255. UTF-8 is also designed so that characters representable in 7-bit ASCII are coded the same; byte values higher than 127 in a UTF-8 string represent the beginning of a multi-byte character.

In fact, like most of PHP’s string functions, this function isn’t doing anything to do with character encoding at all — it is just interpreting a binary byte from a string as an unsigned integer. That is, ord(chr(200)) will always return 200, but what character chr(200) *means* will vary depending on what character encoding it is *interpreted* as part of (e.g. during display).

A technically correct description would be «Returns an integer representation of the first byte of a string, from 0 to 255. For single-byte encodings such as (7-bit) ASCII and the ISO 8859 family, this will correspond to the first character, and will be the position of that character in the encoding’s mapping table. For multi-byte encodings, such as UTF-8 or UTF-16, the byte may not represent a complete character.»

The link to asciitable.com should also be replaced by one which explains what character encoding it is displaying, as «Extended ASCII» is an ambiguous and misleading name.

Источник

mb_ord

Возвращает значение кодовой точки Unicode для данного символа.

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

Параметр encoding представляет собой символьную кодировку. Если он опущен или равен null , вместо него будет использовано значение внутренней кодировки.

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

Кодовая точка Unicode для первого символа string или false в случае возникновения ошибки.

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

Примеры

var_dump ( mb_ord ( «A» , «UTF-8» ));
var_dump ( mb_ord ( «🐘» , «UTF-8» ));
var_dump ( mb_ord ( «\x80» , «ISO-8859-1» ));
var_dump ( mb_ord ( «\x80» , «Windows-1252» ));
?>

Результат выполнения данного примера:

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

  • mb_internal_encoding() — Установка/получение внутренней кодировки скрипта
  • mb_chr() — Возвращает символ по значению кодовой точки Unicode
  • IntlChar::ord() — Получить код символ Unicode
  • ord() — Конвертирует первый байт строки в число от 0 до 255

User Contributed Notes 1 note

$array[‘Б’] = uniord(‘Б’);
$array[‘🚷’] = uniord(‘🚷’);
$array[‘mb_ord Б’] = mb_ord(‘Б’);
$array[‘mb_ord 🚷’] = mb_ord(‘🚷’);

function uniord($charUTF8)
$charUCS4 = mb_convert_encoding($charUTF8, ‘UCS-4BE’, ‘UTF-8’);
$byte1 = ord(substr($charUCS4, 0, 1));
$byte2 = ord(substr($charUCS4, 1, 1));
$byte3 = ord(substr($charUCS4, 2, 1));
$byte4 = ord(substr($charUCS4, 3, 1));
return ($byte1 >

array ( ‘Б’ => 1041, ‘🚷’ => 128695, ‘mb_ord Б’ => 1041, ‘mb_ord 🚷’ => 128695, )

https://unicode-table.com/en/0411/
Б
Encoding hex dec (bytes) dec binary
UTF-8 D0 91 208 145 53393 11010000 10010001
UTF-16BE 04 11 4 17 1041 00000100 00010001
UTF-16LE 11 04 17 4 4356 00010001 00000100
UTF-32BE 00 00 04 11 0 0 4 17 1041 00000000 00000000 00000100 00010001
UTF-32LE 11 04 00 00 17 4 0 0 285474816 00010001 00000100 00000000 00000000

https://unicode-table.com/en/1F6B7/
🚷
Encoding hex dec (bytes) dec binary
UTF-8 F0 9F 9A B7 240 159 154 183 4036991671 11110000 10011111 10011010 10110111
UTF-16BE D8 3D DE B7 216 61 222 183 3627933367 11011000 00111101 11011110 10110111
UTF-16LE 3D D8 B7 DE 61 216 183 222 1037613022 00111101 11011000 10110111 11011110
UTF-32BE 00 01 F6 B7 0 1 246 183 128695 00000000 00000001 11110110 10110111
UTF-32LE B7 F6 01 00 183 246 1 0 3086352640 10110111 11110110 00000001 00000000

  • Функции для работы с многобайтовыми строками
    • mb_​check_​encoding
    • mb_​chr
    • mb_​convert_​case
    • mb_​convert_​encoding
    • mb_​convert_​kana
    • mb_​convert_​variables
    • mb_​decode_​mimeheader
    • mb_​decode_​numericentity
    • mb_​detect_​encoding
    • mb_​detect_​order
    • mb_​encode_​mimeheader
    • mb_​encode_​numericentity
    • mb_​encoding_​aliases
    • mb_​ereg_​match
    • mb_​ereg_​replace_​callback
    • mb_​ereg_​replace
    • mb_​ereg_​search_​getpos
    • mb_​ereg_​search_​getregs
    • mb_​ereg_​search_​init
    • mb_​ereg_​search_​pos
    • mb_​ereg_​search_​regs
    • mb_​ereg_​search_​setpos
    • mb_​ereg_​search
    • mb_​ereg
    • mb_​eregi_​replace
    • mb_​eregi
    • mb_​get_​info
    • mb_​http_​input
    • mb_​http_​output
    • mb_​internal_​encoding
    • mb_​language
    • mb_​list_​encodings
    • mb_​ord
    • mb_​output_​handler
    • mb_​parse_​str
    • mb_​preferred_​mime_​name
    • mb_​regex_​encoding
    • mb_​regex_​set_​options
    • mb_​scrub
    • mb_​send_​mail
    • mb_​split
    • mb_​str_​split
    • mb_​strcut
    • mb_​strimwidth
    • mb_​stripos
    • mb_​stristr
    • mb_​strlen
    • mb_​strpos
    • mb_​strrchr
    • mb_​strrichr
    • mb_​strripos
    • mb_​strrpos
    • mb_​strstr
    • mb_​strtolower
    • mb_​strtoupper
    • mb_​strwidth
    • mb_​substitute_​character
    • mb_​substr_​count
    • mb_​substr

    Источник

    Как получить код символа в кодировке UTF-8?

    Имеется WP. В нем посты в кодировке UTF-8.
    Как получить код символа в кодировке UTF-8?
    Вообще задача большая и мне придутся очень много работать со строками и символами. А наш «любимый» PHP до сих пор не дружит с UTF-8. Если у кого то есть советы по тому как их друг с другом примерить, буду благодарен.

    Как можно получить код символа в какой-либо кодировке?
    Как можно получить код символа в какой-либо кодировке? И какую тогда лучше использовать кодировку.

    Код не выводит символы в кодировке UTF-8, которые представляют из себя суррогатные пары юникода
    Друзья! Продолжаем разбираться с юникодом .Вот код. Он должен выводить таблицу юникода, точнее.

    Как хранить строки в кодировке UTF-8?
    Как сделать, чтобы в строковом типе символы находились в кодировке utf8? в данном коде слово ТЕКСТ.

    Как сделать сайт в кодировке UTF-8?
    Если я правильно понимаю, то для изготовления страницы в кодировке UTF-8 надо не только прописать.

    Спасибо конечно)), но ord определяет код символа в ASCII кодировке (это когда на кодирование символа используется 1 байт). В юнекод другая система.

    Нет). во первых объемы текста довольно большие (несколько миллионов символов) и конвертировать их постоянно это накладно. И во что, например, конвертировать (в ASCII не кириллицы)?)

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    /** * Преобразование кода символа Юникода в символ в UTF-8 * * @param int $code * Код символа из диапазона Юникода. * * @return string * Символ с соответствующим кодом в кодировке UTF-8. * * @throws RangeException */ function codeToUtf8($code) { $code = (int) $code; if ($code  0) { throw new RangeException("Negative value was passed"); } # 0------- elseif ($code  0x7F) { return chr($code); } # 110----- 10------ elseif ($code  0x7FF)  return chr($code >> 6  # 1110---- 10------ 10------ elseif ($code  0xFFFF)  0x80) . chr($code & 0x3F  # 11110--- 10------ 10------ 10------ elseif ($code  0x1FFFFF)  return chr($code >> 18  # 111110-- 10------ 10------ 10------ 10------ elseif ($code  0x3FFFFFF)  0x80) . chr($code & 0x3F  # 1111110- 10------ 10------ 10------ 10------ 10------ elseif ($code  0x7FFFFFFF)  0x80) . chr($code >> 6 & 0x3F  else { throw new RangeException("Invalid character code"); } } /** * Получение кода символа Юникода * * @param string $utf8Char * Символ в кодировке UTF-8. Если в строке содержится больше одного символа * UTF-8, то учитывается только первый. * * @return int * Код символа из Юникода. * * @throws InvalidArgumentException */ function utf8ToCode($utf8Char) { $utf8Char = (string) $utf8Char; if ("" == $utf8Char) { throw new InvalidArgumentException("Empty string is not valid character"); } # [a, b, c, d, e, f] $bytes = array_map('ord', str_split(substr($utf8Char, 0, 6), 1)); # a, [b, c, d, e, f] $first = array_shift($bytes); # 0------- if ($first  0x7F) { return $first; } # 110----- 10------ elseif ($first >= 0xC0 && $first  0xDF) { $tail = 1; } # 1110---- 10------ 10------ elseif ($first >= 0xE0 && $first  0xEF) { $tail = 2; } # 11110--- 10------ 10------ 10------ elseif ($first >= 0xF0 && $first  0xF7) { $tail = 3; } # 111110-- 10------ 10------ 10------ 10------ elseif ($first >= 0xF8 && $first  0xFB) { $tail = 4; } # 1111110- 10------ 10------ 10------ 10------ 10------ elseif ($first >= 0xFC && $first  0xFD) { $tail = 5; } else { throw new InvalidArgumentException("First byte is not valid"); } if (count($bytes)  $tail) { throw new InvalidArgumentException("Corrupted character: $tail tail bytes required"); } $code = ($first & (0x3F >> $tail))  <($tail * 6); $tails = array_slice($bytes, 0, $tail); foreach ($tails as $i => $byte)  $code  return $code; }
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
    foreach ( array(0x21, 0x0410, 0x044B, 0x2116) as $code ) { $char = codeToUtf8($code); $back_code = utf8ToCode($char); printf( "%04x -> %s -> %04x (%s)" , $code , $char , $back_code , ($code === $back_code) ? "+ok" : "!fail" ); echo PHP_EOL; }
    0021 -> ! -> 0021 (+ok) 0410 -> А -> 0410 (+ok) 044b -> ы -> 044b (+ok) 2116 -> № -> 2116 (+ok)

    Источник

    Читайте также:  Hello World
Оцените статью