Home >Backend Development >PHP Tutorial >PHP returns the character function chr() from the specified ASCII value

PHP returns the character function chr() from the specified ASCII value

黄舟
黄舟Original
2017-11-02 09:50:592104browse

Example

Return characters from different ASCII values:

<?php
echo chr(52) . "<br>"; // Decimal value
echo chr(052) . "<br>"; // Octal value
echo chr(0x52) . "<br>"; // Hex value
?>

Definition and usage

chr() FunctionReturns characters from the specified ASCII value.

ASCII values ​​can be specified as decimal, octal, or hexadecimal values. Octal values ​​are defined with leading 0 and hexadecimal values ​​are defined with leading 0x.

Syntax

chr(ascii)
Parameters Description
ascii Required. ASCII value.

Technical details

Return value: Returns the specified character.
PHP version: 4+
##More examples

Use octal values 046 to add the ASCII character: &.

<?php
$str = chr(046);
echo("You $str me forever!");
?>

Example 2

Use decimal values ​​43 and 61 to add ASCII characters: + and =.

<?php 
$str = chr(43);
$str2 = chr(61);
echo("2 $str 2 $str2 4"); 
?>

The chr() function is opposite to the ord() function and is used to return the specified character, such as chr(97) returns a.


Combined with the above example, as long as the ASCII value of the Chinese character is obtained, the Chinese character can be loaded through the chr() function
Array, the code is as follows

$string = "不要迷恋哥"; 
$length = strlen($string); 
var_dump($string);//原始中文 
var_dump($length);//长度 
$result = array(); 
for($i=0;$i<$length;$i++){ 
if(ord($string[$i])>127){ 
$result[] = ord($string[$i]).&#39; &#39;.ord($string[++$i]); 
} 
} 
var_dump($result); 
foreach($result as $v){ 
$decs = explode(" ",$v); 
echo chr($decs[0]).chr($decs[1]); 
}

PHP returns the character function chr() from the specified ASCII value

The above code does not directly output Chinese characters, but prints out normal Chinese characters. The principle is to first obtain the ASCII value of each byte, convert it into bytes through the chr() function, and then convert the two bytes The combination forms a complete Chinese character.



The above is the detailed content of PHP returns the character function chr() from the specified ASCII value. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn