PHPのお勉強!

PHP TOP

chr

(PHP 4, PHP 5, PHP 7, PHP 8)

chr数値から、1バイトの文字列を生成する

説明

chr(int $codepoint): string

codepoint を符号なし数値と解釈することによって指定された文字を含む、 1文字からなる文字列を返します。

この関数は、ASCII, ISO-8859, Windows 1252 のような シングルバイトエンコーディング においては、文字セットのマッピングテーブルにある望みの文字の位置を 渡すことで、一文字の文字列を作り出すのに使えます。 しかし、この関数は string のエンコーディングについて知りませんし、 特に UTF-8 や UTF-16 のようなマルチバイトエンコーディングについては、 この関数に Unicode のコードポイントは渡せないことに注意してください。

この関数はord()の逆の動作をします。

パラメータ

codepoint

0 から 255 までの数値

妥当な範囲 (0..255) 外の値を渡した場合は、255 とのビット AND を行います。 この処理は、以下のコードと同様のアルゴリズムです。

while ($bytevalue < 0) {
$bytevalue += 256;
}
$bytevalue %= 256;

戻り値

指定されたバイトを含む、一文字からなる文字列を返します。

変更履歴

バージョン 説明
7.4.0 codepoint に対して、 サポートされていない入力が与えられた場合、 黙って0 にキャストする動作をしなくなりました。

例1 chr() の例

<?php
// Assumes the string will be used as ASCII or an ASCII-compatible encoding

$str = "この文字列はエスケープで終了します: ";
$str .= chr(27); /* $str の最後にエスケープ文字を付加する */

/* こちらの方がより便利なことが多い */

$str = sprintf("この文字列はエスケープで終了します: %c", 27);
?>

例2 オーバーフローの挙動

<?php
echo chr(-159), chr(833), PHP_EOL;
?>

上の例の出力は以下となります。

aA

例3 個別のバイトから、UTF-8 文字列を組み立てる

<?php
$str
= chr(240) . chr(159) . chr(144) . chr(152);
echo
$str;
?>

上の例の出力は以下となります。


🐘

参考

  • sprintf() - フォーマットされた文字列を返す のフォーマット文字列 %c
  • ord() - 文字列の先頭バイトを、0 から 255 までの値に変換する
  • » ASCII テーブル
  • mb_chr() - Unicode のコードポイントに対応する文字を返す
  • IntlChar::chr() - コードポイント値に対応する、Unicode 文字を返す

add a note

User Contributed Notes 23 notes

up
23
perrodin at laposte dot net
20 years ago
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)
up
16
voromax
15 years ago
Another quick and short function to get unicode char by its code.

<?php
/**
* Return unicode char by its code
*
* @param int $u
* @return char
*/
function unichr($u) {
return
mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
?>
up
8
grey - greywyvern - com
19 years ago
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.

<?php function unichr($dec) {
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:

<?php

$str
= "Chinese: &#20013;&#25991;";
$str = preg_replace("/&#(\d{2,5});/e", "unichr($1);", $str);

?>
up
5
mailderemi at gmail dot com
13 years ago
Here is a sample of encoding and decoding using "chr" and "ord".
<?php
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).'<br>';
echo
Decode(Encode('123',5));
?>
up
3
Noname
2 years ago
<?php

for ($i = 128; $i <= 191; $i++) {
$str = chr(240) . chr(159) . chr(144) . chr($i);
echo
$str;
}

?>
up
2
synnus at gmail dot com
9 years ago
// rivencodec 1.0
// encode riverse ascii 1 simple function can encode/decode
// can use it for secure source with speed encode text

<?php

function rivencodec($ch,$a=0) {
while((@
$b = $ch[$a++])) { $ch[$a-1] = chr(255-ord($b)); }
return
$ch;
}


$zz = rivencodec("abcdefghijklmn");
echo
'encode: ',$zz,'<br/>',PHP_EOL;

$yy = rivencodec($zz);
echo
'decode: ',$yy,'<br/>',PHP_EOL;

?>
up
3
joeldegan AT yahoo.com
22 years ago
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");
?>
up
1
gjarrige at six-axe dot fr
12 years ago
to remove the ASCII control characters (except "line feed" and "tab") :

$tab_chr = array() ;
for($control = 0; $control < 32; $control++) {
if ($control != 9 && $control != 10) {
$tab_chr[]= chr($control) ;
}
}
$tab_chr[]= chr(127) ;
$string = str_replace($tab_chr, '', $string);
up
1
tenyou at gmail dot com
20 years ago
When having to deal with parsing an IIS4 or IIS5 metabase dump I wrote a simple function for converting those MS hexidecimal values into their ascii counter parts. Hopefully someone will find use for it.

<?php
function hex_decode($string) {
for (
$i=0; $i < strlen($string); $i) {
$decoded .= chr(hexdec(substr($string,$i,2)));
$i = (float)($i)+2;
}
return
$decoded;
}
?>
up
1
Josh B.
16 years ago
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.

<?php
$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); // left single guillemet
$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
?>

[1] On the use of some MS Windows characters in HTML
http://www.cs.tut.fi/~jkorpela/www/windows-chars.html

[2] Unicode Explained by Jukka Korpela
http://www.amazon.com/dp/059610121X/
up
1
scott at quinlan dot co dot nz
16 years ago
Secure password generator with a variable maximum amount of symbols.

<?php

function passwdGen($minLength = 8, $maxLength = 12, $maxSymbols = 2)
{
$symbolCount = 0;

srand((double)microtime() * 1000003);

for (
$i = 0; $i < rand($minLength, $maxLength); $i++)
{
do
{
$char = rand(33, 126);

$symbolCount += $isSymbol = (!in_array($char, range(48, 57)) && !in_array($char, range(65, 90)) && !in_array($char, range(97, 122)));

if (
$symbolCount <= $maxSymbols || !$isSymbol)
{
break;
}
}
while (
true);

$passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, $char);
}

return
$passwd;
}

?>
up
1
happyevil(at)1218.org
23 years ago
Here is a function that's help me find what chr(number) outputs what character quicker than typing out 256 echo tags.

<?php
function listChr(){
for (
$i = 0; $i < 256; ++$i) {
static
$genNum;
$genNum++;
echo
"chr($genNum) will output '";
echo (
chr($genNum));
echo
"'< br>\n";
}
}
listChr();
?>

Another helpful chr is #9, being a tab. Quite using when making error logs.

$tab = (chr(9));
echo "<pre>error{$tab}date{$tab}time</pre>";

-- HappyEvil
up
0
Ray.Paseur sometimes uses Gmail
5 years ago
I needed to generate an invalid UTF-8 character for testing with JSON. This did the trick:

<?php
echo 'Bogus UTF-8 character at end' . chr(0xC6) ;
up
0
vitkorob
8 years ago
Another quick function to get unicode char by its code.

<?php

function unichr($dec)
{
if (
$dec < 0x80)
{
$utf = chr($dec);
}
else if (
$dec < 0x0800)
{
$utf = chr(0xC0 + ($dec >> 6));
$utf .= chr(0x80 + ($dec & 0x3f));
}
else if (
$dec < 0x010000)
{
$utf = chr(0xE0 + ($dec >> 12));
$utf .= chr(0x80 + (($dec >> 6) & 0x3f));
$utf .= chr(0x80 + ($dec & 0x3f));
}
else if (
$dec < 0x200000)
{
$utf = chr(0xF0 + ($dec >> 18));
$utf .= chr(0x80 + (($dec >> 12) & 0x3f));
$utf .= chr(0x80 + (($dec >> 6) & 0x3f));
$utf .= chr(0x80 + ($dec & 0x3f));
}
else
{
die(
"UTF-8 character size is more than 4 bytes");
}

return
$utf;
}

echo
unichr(0x263A);

?>
up
0
darek at module17 dot com
11 years ago
Simple password generation function using sprintf and the %c type specifier; which is the same as chr().

function genPass($len = 8) {
for ($i=0;$i<=$len;$i++) {
$passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, rand(48, 122));
}
return $passwd;
}
up
0
ddawsonNOSPAM at execpc dot com
24 years ago
[Editor's note:

%c is defined as: "Print the character belonging to the ascii code given"

chr() just gives a string, so you need to use %s, even if the string consists of only one character. This is consistent with other languages.
--Jeroen@php.net]


Learn from my mistake:
Do not expect this to work!

<?php
$c_question
= chr(63);
$v_out = sprintf("<%cphp\n", $c_question);
//... more stuff being sprintf'd into v_out here ...
$v_out = sprintf("%s%c>\n", $v_out, $c_question);
$v_fp = fopen("foofile", "w");
if (
$v_fp)
{
fwrite($v_fp, $v_out, strlen($v_out));
fclose($v_fp);
}
?>

When I did this, foofile contained <NUL NUL NUL NUL NUL>.
I spun my wheels quite awhile looking at fputs, fwrite to verify I was calling those functions correctly.
My mistake was using $c_question = chr(63) instead of
$c_question = 63 (correct). Then everything worked fine.
up