chr

(PHP 4, PHP 5, PHP 7)

chr返回指定的字符

说明

string chr ( int $ascii )

返回相对应于 ascii 所指定的单个字符。

此函数与 ord() 是互补的。

参数

ascii

Ascii 码。

返回值

返回规定的字符。

范例

Example #1 chr() 例子

<?php
$str 
"The string ends in escape: ";
$str .= chr(27); /* 在 $str 后边增加换码符 */

/* 通常这样更有用 */

$str sprintf("The string ends in escape: %c"27);
?>

参见

User Contributed Notes

vitkorob 09-Feb-2016 10:01
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);

?>
synnus at gmail dot com 11-Sep-2015 05:34
// 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;

?>
lingtalfi - at - somewhere 13-Jun-2015 03:09
It seems that php uses the table from here: http://ascii-code.com/
(and not from here: http://www.asciitable.com/ as suggested in the documentation) for codes from 128 to 255.

<?php
for ($i = 32; $i <= 255; $i++) {
    echo
chr($i);
}
?>
fernandobasso dot br at gmail dot com 02-May-2015 06:24
The help mentions a link to an ascii table. On some *nix systems you can simply do `man ascii`.
Pascal 02-Sep-2014 08:01
function ascii2str($str) {
    $arr=array(
        "&#32;"=>' ', "&#33;"=>'!', "&#34;"=>'"', "&#35;"=>'#', "&#36;"=>'$',
        "&#37;"=>'%', "&#38;"=>'&', "&#39;"=>"'", "&#40;"=>'(', "&#41;"=>')',
        "&#42;"=>'*', "&#43;"=>'+', "&#44;"=>',', "&#45;"=>'-', "&#46;"=>'.',
        "&#47;"=>'/', "&#48;"=>'0', "&#49;"=>'1', "&#50;"=>'2', "&#51;"=>'3',
        "&#52;"=>'4', "&#53;"=>'5', "&#54;"=>'6', "&#55;"=>'7', "&#56;"=>'8',
        "&#57;"=>'9', "&#58;"=>':', "&#59;"=>';', "&#60;"=>'<', "&#61;"=>'=',
        "&#62;"=>'>', "&#63;"=>'?', "&#64;"=>'@', "&#65;"=>'A', "&#66;"=>'B',
        "&#67;"=>'C', "&#68;"=>'D', "&#69;"=>'E', "&#70;"=>'F', "&#71;"=>'G',
        "&#72;"=>'H', "&#73;"=>'I', "&#74;"=>'J', "&#75;"=>'K', "&#76;"=>'L',
        "&#77;"=>'M', "&#78;"=>'N', "&#79;"=>'O', "&#80;"=>'P', "&#81;"=>'Q',
        "&#82;"=>'R', "&#83;"=>'S', "&#84;"=>'T', "&#85;"=>'U', "&#86;"=>'V',
        "&#87;"=>'W', "&#88;"=>'X', "&#89;"=>'Y', "&#90;"=>'Z', "&#91;"=>'[',
        "&#92;"=>'\\', "&#93;"=>']', "&#94;"=>'^', "&#95;"=>'_', "&#96;"=>'`',
        "&#97;"=>'a', "&#98;"=>'b', "&#99;"=>'c', "&#100;"=>'d', "&#101;"=>'e',
        "&#102;"=>'f', "&#103;"=>'g', "&#104;"=>'h', "&#105;"=>'i', "&#106;"=>'j',
        "&#107;"=>'k', "&#108;"=>'l', "&#109;"=>'m', "&#110;"=>'n', "&#111;"=>'o',
        "&#112;"=>'p', "&#113;"=>'q', "&#114;"=>'r', "&#115;"=>'s', "&#116;"=>'t',
        "&#117;"=>'u', "&#118;"=>'v', "&#119;"=>'w', "&#120;"=>'x', "&#121;"=>'y',
        "&#122;"=>'z', "&#123;"=>'{', "&#124;"=>'|', "&#125;"=>'}', "&#126;"=>'~'
    );
    return strtr($str,$arr);
}
v14t at gmx dot com 01-Apr-2014 02:58
argument is automatically converted to integer, so chr('65') and chr(65) would both output the letter A
darek at module17 dot com 07-Mar-2013 04:45
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;
}
krkbpk at gmail dot com RamaKrishna Kothamasu 08-Feb-2013 01:11
//simple example for chr() function
<?php
$i
=0;
for(
$i;$i<=255;$i++)
{
    echo
chr($i)."<br>";
}
?>
gjarrige at six-axe dot fr 01-Mar-2012 06:47
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);
mailderemi at gmail dot com 04-Feb-2011 05:17
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));
?>
sinfocol at sinfocol dot org 30-Jun-2009 11:38
The function chr() also accepts negative numbers as an ascii code, so chr(-number) is equal to chr((number%256)+256).
And for ascii code higher than 255 is chr(number%256)

We can test with a little script
<?php
   
for($i=-300; $i<300; $i++){
        echo
"Ascii $i\t" . ord(chr($i)) . "\n";
    }
?>
voromax 31-Jan-2009 04:39
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');
}
?>
jacob at loggy punt nl 31-Dec-2008 02:46
This function creates a ascii table, and replaces all the ascii characters in the mail.
---
Deze functie maakt een ascii tabel, en zet alles juist om.

<?php
 
function makeASCII($a){
 
$find[] = "=\r\n";
 
$replace[] = "";
 
  for(
$i=0; $i < 256; $i++){
   
$find[] = "=".dechex($i)."";
   
$replace[] = chr($i);
  }
 
$a = str_replace($find,$replace,$a);
  return
$a;
 }
?>
scott at quinlan dot co dot nz 21-Oct-2008 06:51
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;
}

?>
Josh B. 12-Aug-2008 11:06
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/
darkodemon at gmail dot com 27-Apr-2007 01:33
chr() with unicode support

<?php

function uchr ($codes) {
    if (
is_scalar($codes)) $codes= func_get_args();
   
$str= '';
    foreach (
$codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
    return
$str;
}

echo
uchr(23383); echo '<br/>';
echo
uchr(23383,215,23383); echo '<br/>';
echo
uchr(array(23383,215,23383,215,23383)); echo '<br/>';

?>
mwgamera at gmail dot com 22-Aug-2006 05:20
Unicode version of chr() using mbstring
<?php
 
function unichr($u) {
    return
mb_convert_encoding(pack("N",$u), mb_internal_encoding(), 'UCS-4BE');
  }
?>
It returns a string in internal encoding (possibly more than one byte).
JasonLauDotBiz 17-Feb-2006 04:34
I didn't see it here, so here's simple random string generation using char.

<?php
for($i=0; $i<7; $i++){
   
$random_string .= chr(rand(0,25)+65);
}
echo
$random_string;
?>
grey - greywyvern - com 19-Aug-2005 04:55
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);

?>
sarabas at itstudio dot pl 17-Feb-2005 01:26
The following function helped me to generate ascii-only usernames from firstname/lastname containing iso-8859-2 characters. The convertion array was based on contents of 'man iso-8859-2'.

Example: iso2ascii("b&#322;a&#380;ej.&#378;d&#378;b&#322;o") returns "blazej.zdzblo"

<?php
function iso2ascii($str) {
 
$arr=array(
 
chr(161)=>'A', chr(163)=>'L', chr(165)=>'L', chr(166)=>'S', chr(169)=>'S',
 
chr(170)=>'S', chr(171)=>'T', chr(172)=>'Z', chr(174)=>'Z', chr(175)=>'Z',
 
chr(177)=>'a', chr(179)=>'l', chr(181)=>'l', chr(182)=>'s', chr(185)=>'s',
 
chr(186)=>'s', chr(187)=>'t', chr(188)=>'z', chr(190)=>'z', chr(191)=>'z',
 
chr(192)=>'R', chr(193)=>'A', chr(194)=>'A', chr(195)=>'A', chr(196)=>'A',
 
chr(197)=>'L', chr(198)=>'C', chr(199)=>'C', chr(200)=>'C', chr(201)=>'E',
 
chr(202)=>'E', chr(203)=>'E', chr(204)=>'E', chr(205)=>'I', chr(206)=>'I',
 
chr(207)=>'D', chr(208)=>'D', chr(209)=>'N', chr(210)=>'N', chr(211)=>'O',
 
chr(212)=>'O', chr(213)=>'O', chr(214)=>'O', chr(216)=>'R', chr(217)=>'U',
 
chr(218)=>'U', chr(219)=>'U', chr(220)=>'U', chr(221)=>'Y', chr(222)=>'T',
 
chr(223)=>'s', chr(224)=>'r', chr(225)=>'a', chr(226)=>'a', chr(227)=>'a',
 
chr(228)=>'a', chr(229)=>'l', chr(230)=>'c', chr(231)=>'c', chr(232)=>'c',
 
chr(233)=>'e', chr(234)=>'e', chr(235)=>'e', chr(236)=>'e', chr(237)=>'i',
 
chr(238)=>'i', chr(239)=>'d', chr(240)=>'d', chr(241)=>'n', chr(242)=>'n',
 
chr(243)=>'o', chr(244)=>'o', chr(245)=>'o', chr(246)=>'o', chr(248)=>'r',
 
chr(249)=>'u', chr(250)=>'u', chr(251)=>'u', chr(252)=>'u', chr(253)=>'y',
 
chr(254)=>'t'
 
);
 return
strtr($str,$arr);
}
?>
tenyou at gmail dot com 15-Jul-2004 08:05
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;
}
?>
perrodin at laposte dot net 12-Apr-2004 01:20
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)
jgray at triangle dash solutions dot com 25-Jul-2003 07:20
Lowercase alphabet:
<?php for($a=97;$a<(97+26);$a++){ echo chr($a); } ?>
infoserv at chollian dot net 25-Jun-2003 05:16
Cutting Korean(2Byte)-String

<?php
function cutStr($str,$len){
    if(
strlen($str) > $len){
       
$str = substr($str,0,$len - 2);
        if(
strlen(substr(strrchr($str," "),1)) % 2)
           
$str = substr($str,0,strlen($str) - 1);
       
$str .= "..";
    }
    return
$str;
}
?>
Kristin 07-Mar-2003 05:19
Note that chr(10) is a 'line feed' and chr(13) is a 'carriage return' and they are not the same thing! I found this out while attempting to parse text from forms and text files for inclusion as HTML by replacing all the carriage returns with <BR>'s only to find after many head-scratchings that I should have been looking for line feeds. If anyone can shed some light on what the difference is, please do.

If you're planning on saving text from a form into a database for later display, you'll need to apply the following function so that it gets saved with the proper HTML tags.

<?php
$text
= str_replace ( chr(10), "<BR>", $text );
?>

When you want to plug it back into that form for editing you need to convert it back.

<?php
$text
= str_replace ( "<BR>", chr(10), $text)
?>

Hope this saves somebody some trouble. :)
joeldegan AT yahoo.com 14-Dec-2002 11:53
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");
?>
webmaster at project-enigma dot net 13-Apr-2002 09:51
\n == &#13;
Usefull if u want to display multi-line-alt-strings
e.g. <img src="/gifs/php_logo.gif" alt="Here u can see the&#13;PHPLogo&#13;3rd line">
happyevil(at)1218.org 27-Mar-2001 04:31
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
ddawsonNOSPAM at execpc dot com 10-May-2000 01:59
[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.