- Php символ по его коду
- Описание
- Список параметров
- Возвращаемые значения
- Список изменений
- Примеры
- Php символ по его коду
- Description
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 23 notes
- Php символ по его коду
- Description
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 6 notes
- PHP chr() Function
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Php символ по его коду
chr — Генерирует односимвольную строку по заданному числу
Описание
Возвращает строку из одного символа, код которого задан аргументом codepoint , который интерпретируется как беззнаковое целое (unsigned integer).
Может использоваться для создания строки из одного символа однобайтовой кодировки, например, такой как ASCII, ISO-8859 или Windows 1252, путем указания позиции этого символа в таблице кодировки. Данная функция не подходит для генерации односимвольной строки в многобайтовых кодировках, таких как UTF-8 или UTF-16.
Эта функция дополняет функцию ord() .
Список параметров
Значения за пределом диапазона (0..255) должны быть побитово сложены (побитовое И) с 255, что соответствует такому алгоритму:
Возвращаемые значения
Строка из одного символа, содержащая заданный байт.
Список изменений
Версия | Описание |
---|---|
7.4.0 | Функция больше не принимает неподдерживаемые значения codepoint и преобразует их в 0 . |
Примеры
Пример #1 Пример использования chr()
// Предполагается, что строка будет использовака как ASCII или ASCII-совместимая
?php
$str = «Эта строка заканчивается на escape: » ;
$str .= chr ( 27 ); /* добавляет символ escape в конец $str */
/* Но обычно лучше использовать такую конструкцию */
$str = sprintf ( «Эта строка заканчивается на escape: %c» , 27 );
?>
Пример #2 Поведение при переполнении
Результат выполнения данного примера:
Пример #3 Создание строки UTF-8 из индивидуальных байтов
Результат выполнения данного примера:
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 — 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() Function
The chr() function returns a character from the specified ASCII value.
The ASCII value can be specified in decimal, octal, or hex values. Octal values are defined by a leading 0, while hex values are defined by a leading 0x.
Syntax
Parameter Values
Technical Details
More Examples
Example
Using the octal value 046 to add the ASCII Character: &.
Example
Using the decimal values 43 and 61 to add the ASCII Characters: + and =.
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.