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 ;
>
?>?php
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.
Php узнать код символа
chr — Generate a single-byte string from a number
Description
Returns a one-character string containing the character specified by interpreting codepoint as an unsigned integer.
This can be used to create a one-character string in a single-byte encoding such as ASCII, ISO-8859, or Windows 1252, by passing the position of a desired character in the encoding’s mapping table. However, note that this function is not aware of any string encoding, and in particular cannot be passed a Unicode code point value to generate a string in a multibyte encoding like UTF-8 or UTF-16.
This function complements ord() .
Parameters
An integer between 0 and 255.
Values outside the valid range (0..255) will be bitwise and’ed with 255, which is equivalent to the following algorithm:
Return Values
A single-character string containing the specified byte.
Changelog
Version | Description |
---|---|
7.4.0 | The function no longer silently accepts unsupported codepoint s, and casts these to 0 . |
Examples
Example #1 chr() example
// Assumes the string will be used as ASCII or an ASCII-compatible encoding
?php
$str = «The string ends in escape: » ;
$str .= chr ( 27 ); /* add an escape character at the end of $str */
/* Often this is more useful */
$str = sprintf ( «The string ends in escape: %c» , 27 );
?>
Example #2 Overflow behavior
The above example will output:
Example #3 Building a UTF-8 string from individual bytes
The above example will output:
See Also
- sprintf() — Return a formatted string with a format string of %c
- ord()
- An » ASCII-table
- mb_chr()
- IntlChar::chr()
User Contributed Notes 23 notes
Note that if the number is higher than 256, it will return the number mod 256.
For example :
chr(321)=A because A=65(256)
Another quick and short function to get unicode char by its code.
/**
* Return unicode char by its code
*
* @param int $u
* @return char
*/
function unichr ( $u ) return mb_convert_encoding ( ‘&#’ . intval ( $u ) . ‘;’ , ‘UTF-8’ , ‘HTML-ENTITIES’ );
>
?>
for ( $i = 128 ; $i $str = chr ( 240 ) . chr ( 159 ) . chr ( 144 ) . chr ( $i );
echo $str ;
>
I spent hours looking for a function which would take a numeric HTML entity value and output the appropriate UTF-8 bytes. I found this at another site and only had to modify it slightly; so I don’t take credit for this.
if ( $dec < 128 ) <
$utf = chr ( $dec );
> else if ( $dec < 2048 ) <
$utf = chr ( 192 + (( $dec — ( $dec % 64 )) / 64 ));
$utf .= chr ( 128 + ( $dec % 64 ));
> else <
$utf = chr ( 224 + (( $dec — ( $dec % 4096 )) / 4096 ));
$utf .= chr ( 128 + ((( $dec % 4096 ) — ( $dec % 64 )) / 64 ));
$utf .= chr ( 128 + ( $dec % 64 ));
>
return $utf ;
> ?>
So for example:
Here is a sample of encoding and decoding using «chr» and «ord».
function Encode ( $txtData , $Level ) for ( $j = 0 ; $j < $Level ; $j ++)$tmpStr = '' ;
for ( $i = 0 ; $i < strlen ( $txtData ); $i ++)
$tmpStr .= ord ( substr ( strtoupper ( $txtData ), $i , 1 ));
$txtData = $tmpStr ;
>
return ( strlen ( $Level )). $Level . $txtData ;
>
function Decode ( $txtData ) $intLevel = substr ( $txtData , 1 , substr ( $txtData , 0 , 1 ));
$startStr = substr ( $txtData , substr ( $txtData , 0 , 1 )+ 1 , strlen ( $txtData ));
for ( $j = 0 ; $j < $intLevel ; $j ++)for ( $i = 0 ; $i < strlen ( $startStr ); $i += 2 )
$tmpStr .= chr ( intval ( substr ( $startStr , $i , 2 )));
$startStr = $tmpStr ;
$tmpStr = «» ;
>
return $startStr ;
>
echo Encode ( ‘123’ , 4 ). ‘
‘ ;
echo Decode ( Encode ( ‘123’ , 5 ));
?>
Want terminal colors in command line php scripts?
This should take care of that.
$_colors = array(
‘LIGHT_RED’ => «[1;31m»,
‘LIGHT_GREEN’ => «[1;32m»,
‘YELLOW’ => «[1;33m»,
‘LIGHT_BLUE’ => «[1;34m»,
‘MAGENTA’ => «[1;35m»,
‘LIGHT_CYAN’ => «[1;36m»,
‘WHITE’ => «[1;37m»,
‘NORMAL’ => «[0m»,
‘BLACK’ => «[0;30m»,
‘RED’ => «[0;31m»,
‘GREEN’ => «[0;32m»,
‘BROWN’ => «[0;33m»,
‘BLUE’ => «[0;34m»,
‘CYAN’ => «[0;36m»,
‘BOLD’ => «[1m»,
‘UNDERSCORE’ => «[4m»,
‘REVERSE’ => «[7m»,
function termcolored($text, $color=»NORMAL», $back=1) <
global $_colors;
$out = $_colors[«$color»];
if($out == «») < $out = "[0m"; >
if($back) <
return chr(27).»$out$text».chr(27).chr(27).»[0m».chr(27);
>else <
echo chr(27).»$out$text».chr(27).chr(27).»[0m».chr(27);
>//fi
>// end function
echo termcolored(«test\n», «BLUE»);
?>
// rivencodec 1.0
// encode riverse ascii 1 simple function can encode/decode
// can use it for secure source with speed encode text
function rivencodec ( $ch , $a = 0 ) while((@ $b = $ch [ $a ++])) < $ch [ $a - 1 ] = chr ( 255 - ord ( $b )); >
return $ch ;
>
$zz = rivencodec ( «abcdefghijklmn» );
echo ‘encode: ‘ , $zz , ‘
‘ , PHP_EOL ;
$yy = rivencodec ( $zz );
echo ‘decode: ‘ , $yy , ‘
‘ , PHP_EOL ;
In addition to replacing Microsoft Windows smart quotes, as sgaston demonstrated on 2006-02-13, I replace all other Microsoft Windows characters using suggestions[1] published by character code specialist[2] Jukka Korpela.
$str = str_replace ( chr ( 130 ), ‘,’ , $str ); // baseline single quote
$str = str_replace ( chr ( 131 ), ‘NLG’ , $str ); // florin
$str = str_replace ( chr ( 132 ), ‘»‘ , $str ); // baseline double quote
$str = str_replace ( chr ( 133 ), ‘. ‘ , $str ); // ellipsis
$str = str_replace ( chr ( 134 ), ‘**’ , $str ); // dagger (a second footnote)
$str = str_replace ( chr ( 135 ), ‘***’ , $str ); // double dagger (a third footnote)
$str = str_replace ( chr ( 136 ), ‘^’ , $str ); // circumflex accent
$str = str_replace ( chr ( 137 ), ‘o/oo’ , $str ); // permile
$str = str_replace ( chr ( 138 ), ‘Sh’ , $str ); // S Hacek
$str = str_replace ( chr ( 139 ), ‘ $str = str_replace ( chr ( 140 ), ‘OE’ , $str ); // OE ligature
$str = str_replace ( chr ( 145 ), «‘» , $str ); // left single quote
$str = str_replace ( chr ( 146 ), «‘» , $str ); // right single quote
$str = str_replace ( chr ( 147 ), ‘»‘ , $str ); // left double quote
$str = str_replace ( chr ( 148 ), ‘»‘ , $str ); // right double quote
$str = str_replace ( chr ( 149 ), ‘-‘ , $str ); // bullet
$str = str_replace ( chr ( 150 ), ‘-‘ , $str ); // endash
$str = str_replace ( chr ( 151 ), ‘—‘ , $str ); // emdash
$str = str_replace ( chr ( 152 ), ‘~’ , $str ); // tilde accent
$str = str_replace ( chr ( 153 ), ‘(TM)’ , $str ); // trademark ligature
$str = str_replace ( chr ( 154 ), ‘sh’ , $str ); // s Hacek
$str = str_replace ( chr ( 155 ), ‘>’ , $str ); // right single guillemet
$str = str_replace ( chr ( 156 ), ‘oe’ , $str ); // oe ligature
$str = str_replace ( chr ( 159 ), ‘Y’ , $str ); // Y Dieresis
?>
http://www.cs.tut.fi/~jkorpela/www/windows-chars.html
Secure password generator with a variable maximum amount of symbols.
function passwdGen ( $minLength = 8 , $maxLength = 12 , $maxSymbols = 2 )
$symbolCount = 0 ;
srand ((double) microtime () * 1000003 );
$passwd = sprintf ( ‘%s%c’ , isset( $passwd ) ? $passwd : NULL , $char );
>
Php узнать код символа
ord-преобразование первого байта строки в значение от 0 до 255
Description
Интерпретирует двоичное значение первого байта character как целое число без знака от 0 до 255.
Если строка находится в однобайтовой кодировке,например,ASCII,ISO-8859 или Windows 1252,это эквивалентно возвращению положения символа в таблице отображения набора символов.Однако,обратите внимание,что эта функция не знает никакой кодировки строки,и,в частности,никогда не будет идентифицировать точку кода Юникода в многобайтовой кодировке,такой как UTF-8 или UTF-16.
Parameters
Return Values
Examples
Пример # 1 Ord () Пример
$str = "\n"; if (ord($str) == 10) < echo "The first character of \$str is a line feed.\n"; > ?>
Пример # 2 Исследование отдельных байтов строки UTF-8
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; > ?>
Выводится приведенный выше пример:
Байт 0 из $str имеет значение 240
Байт 1 из $str имеет стоимость 159
Байт 2 из $str имеет значение 144
Байт 3 из $str имеет значение 152
See Also
- chr () — генерирует однобайтовую строку из числа
- » ASCII -таблица
- mb_ord () — Получить код символа Unicode
- IntlChar :: ord () — Возвращает значение кодовой точки Unicode символа
PHP 8.2
(PHP 4 4.0.6,5,7,8)openssl_x509_read Разбирает сертификат и возвращает объект для него openssl_x509_read()разбирает сертификат,предоставленный и возвращает
(PHP 7 7.4.0,8)openssl_x509_verify Проверяет цифровую подпись сертификата относительно открытого ключа openssl_x509_verify()проверяет,что сертификат был
(PHP 4 4.3.0,5,7,8)output_add_rewrite_var Значения механизма перезаписи URL Эта функция добавляет еще одну пару имя/значение в механизм перезаписи URL.
(PHP 4 4.3.0,5,7,8)output_reset_rewrite_vars Значения рерайтера URL Эта функция сбрасывает значения рерайтера URL и удаляет все переменные,которые ранее были удалены функцией output_add_rewrite_var().