search for in the  
<chopchunk_split>
Last updated: Thu, 19 May 2005

chr

(PHP 3, PHP 4, PHP 5)

chr -- Return a specific character

Description

string chr ( int ascii )

Returns a one-character string containing the character specified by ascii.

Example 1. chr() example

<?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);
?>

You can find an ASCII-table over here: http://www.asciitable.com.

This function complements ord(). See also sprintf() with a format string of %c.



User Contributed Notes
chr
mike at go dot online dot pt
11-Mar-2005 02:18
In addition to what mcusack wrote about new lines in text files under Windows:

<?php
$text
= "First line\r\n";
$text .= "Second line";
echo
$text;
?>
Will output:
First lineSecond line

<?php
$text
= "First line" . chr(13) . chr(10);
$text .= "Second line";
echo
$text;
?>
Will output:
First line
Second line
sarabas at itstudio dot pl
17-Feb-2005 06: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"

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);
}
15-Dec-2004 12:04
Same function as suggested by tippy2k/jmartin. tippy2k's code seems to have a syntax error in the function declaration; jmartin's code throws a notice.
So here's yet another version, without temporary variables and loops:

<?
// 1 <= $a <= 702
function col2str($a) {
 return (
$a-->26?chr(($a/26+25)%26+ord('A')):'').chr($a%26+ord('A'));
}

// Example
$colname = col2str(1) // returns "A"
$colname = col2str(27) // returns "AA"
$colname = col2str(702) // returns "ZZ"
?>
jon
15-Sep-2004 06:11
in response to jcokos's function for catching non-Ascii values when converting to entitites for XML.

I have found it better to use htmlspecialchars rather than htmlentities because htmlentities does convert some non-Ascii characters to entitities, for example the copyright symbol. To be fully compliant with XML, the numeric entity should be used, rather than the symbolic version used in htmlentities.

<?php
  
function strictify ( $string ) {

      
$fixed = htmlspecialchars( $string, ENT_QUOTES );

      
$trans_array = array();
       for (
$i=127; $i<255; $i++) {
          
$trans_array[chr($i)] = "&#" . $i . ";";
       }

      
$really_fixed = strtr($fixed, $trans_array);

       return
$really_fixed;

   }
?>
tenyou at gmail dot com
15-Jul-2004 01: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;
}
?>
tippy2k
13-May-2004 09:27
Working on the same thing as jmartin today.  701 is the limit of the script, 'ZZ'.  This should work a little faster.  Hope it helps.

<?
function SSkey($xkey+1) {
  
$prefix = chr(floor($xkey+1 / 26)+64);
   if(
$prefix == chr(64)) unset($prefix);
  
$suffix = chr($xkey+1 - (floor($xkey+1 / 26)*26) +64);
   if(
$suffix == chr(64)) {
      
$prefix = chr( ord($prefix) -1);
       if(
$prefix == chr(64)) unset($prefix);
      
$suffix = 'Z';
   }
  
$sskey = "$prefix$suffix";
   return
$sskey;
}
?>
jmartin at prescientsoftware dot com
13-Apr-2004 04:42
Here is a function that will convert column numbers in to a letters for use in a spreadsheet.  It is limited up to 'ZZ' but can easliy by modifed.

<?php
 
function col2chr($a){
       if(
$a<27){
           return
strtoupper(chr($a+96));   
       }else{
           while(
$a > 26){
              
$b++;
              
$a = $a-26;               
           }                 
          
$b = strtoupper(chr($b+96));   
          
$a = strtoupper(chr($a+96));               
           return
$b.$a;
       }
   }
?>
perrodin at laposte dot net
11-Apr-2004 06: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)
goffrie at somewhere dot ca
05-Apr-2004 07:06
ASCII 7 makes a beep.
so
print chr(7);
is useful in long scripts (like ones that download big files) when you want to get the user's attention after a long time of waiting.
---------------------
Me:)
---------------------
mcusack at fastlanecompanies dot com
25-Mar-2004 06:46
when working with output to a windows system i.e. a textfile the end of line "\n" will not return a valid newline that windows will understand (this is due to a lack of standards accross OS types) this is because windows reads new lines as carriage return and an additional char the linefeed the traditional "\n" so in short use the following to produce a new line under a windows text environment "\r\n"

// not tested but this should work in most cases (i think....)

<?php
function win_nl2br($stringtext) {
return
str_replace("\r\n", "<br>", $stringtext);
}

function
win_br2nl($stringtext) {
return
str_replace("<br>", "\r\n", $stringtext);
}
?>

Hope this is as informative to you as it was to me ......
loremaster
09-Sep-2003 03:27
Re: Kristin: Line feed vs carriage return

I may be wrong, it's been a while since I cared about the difference.

Line feeds add a new line below the current carriage position and moves the carriage to it.
Carriage return brings the carriage (or cursor, if you like) to the beginning of the line.

Most mutliline text fields, when you press Enter, you get both a line feed (new line) and a carriage return (return).  Typically I use the strtr function and replace "\n\r" rather than searching for ascii 13 and 10.  There are many ways, of course, so your mileage may vary.
jgray at triangle dash solutions dot com
25-Jul-2003 12:20
Lowercase alphabet:
for($a=97;$a<(97+26);$a++){ echo chr($a); }
infoserv at chollian dot net
24-Jun-2003 10: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;
}
?>
jcokos
26-Mar-2003 08:12
A quick function that I use to make strings "XML" compliant, changing every special character into their #$... equivalent.

htmlentities doesn't get all of the chars above 127, so the second part of this (which I stole from one of the comments above) finishes the process, returning a nice, xml happy string.

<?php
  
function strictify ( $string ) {

      
$fixed = htmlentities( $string, ENT_QUOTES );

      
$trans_array = array();
       for (
$i=127; $i<255; $i++) {
          
$trans_array[chr($i)] = "&#" . $i . ";";
       }

      
$really_fixed = strtr($fixed, $trans_array);

       return
$really_fixed;

   }
?>

HTH
avenger at php dot net
22-Mar-2003 03:26
I usally used this code to test a Chinese string:

<?php
$chinese_str
= "³Â²®ÀÖ";
if (
preg_match("/^[".chr(0xa1)."-".chr(0xff)."_-]+$/",$chinese_str) {
   echo
'This is a Chinese word..';
} else {
   echo
'This is not a Chinese word..';
}
?>
Kristin
06-Mar-2003 10: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 04: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");
?>
gschafer at robandger dot com
08-Nov-2002 06:17
Here's a small function I wrote up to generate random passwords using the chr() function.

<?php
function randPass($len)
{
 
$pw = ''; //intialize to be blank
 
for($i=0;$i<$len;$i++)
 {
   switch(
rand(1,3))
   {
     case
1: $pw.=chr(rand(48,57));  break; //0-9
    
case 2: $pw.=chr(rand(65,90));  break; //A-Z
    
case 3: $pw.=chr(rand(97,122)); break; //a-z
  
}
 }
 return
$pw;
}
?>

Example:

<?php
 $password
= randPass(10); //assigns 10-character password
?>

I found this useful in my early coding days... I'm sure someone else will too :D
28-Jun-2002 10:05
This bit of code will convert all those lovely tilde,umlaut etc. etc. characters into safe character codes:

<?php
   $trans_array
= array();
   for (
$i=127; $i<255; $i++) {
      
$trans_array[chr($i)] = "&#" . $i . ";";
   }
  
$outtext = strtr($intext, $trans_array);
?>
webmaster at project-enigma dot net
13-Apr-2002 02: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
26-Mar-2001 09: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
09-May-2000 06: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.

<chopchunk_split>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT