Главная | Руководство по MySQL | MySQL Manual | Документация к HTTP серверу Apache | Apache HTTP Server Documentation | downloads | faq

искать  Язык: Английский


chr

(PHP 4, PHP 5)

chrВозвращает символ по его коду

Описание

string chr ( int $ascii )

Возвращает строку из одного символа, код которого задан аргументом ascii .

Пример #1 Пример использования chr()

<?php
$str 
"Эта строка окачивается escape: ";
$str .= chr(27); /* добавляет escape-символ в конец $str */

/* Но часто лучше использовать такую конструкцию */

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

Таблицу ASCII-кодов вы можете найти здесь: » http://www.asciitable.com.

Эта функция дополняет функцию ord(). См. также описание формата %c функции sprintf().


User Contributed Notes
chr
Icar
11-Mar-2010 04:31
Here is code for generation Russian alphabet:
<?php
for ($i=176;$i<=207;++$i) {
    echo
$i.'='.iconv('ISO-8859-5', 'UTF-8', chr($i)).'<br>';
}
?>
This simple code generates all Russian capital letters, but without '�_'.
Emprivo.com
01-Sep-2009 02:36
<?php
/*==================================
Replaces special characters with non-special equivalents
==================================*/
function normalize_special_characters( $str )
{
   
# Quotes cleanup
   
$str = ereg_replace( chr(ord("`")), "'", $str );        # `
   
$str = ereg_replace( chr(ord("�_")), "'", $str );        # �_
   
$str = ereg_replace( chr(ord("�__")), ",", $str );        # �__
   
$str = ereg_replace( chr(ord("`")), "'", $str );        # `
   
$str = ereg_replace( chr(ord("�_")), "'", $str );        # �_
   
$str = ereg_replace( chr(ord("�__")), "\"", $str );        # �__
   
$str = ereg_replace( chr(ord("�__")), "\"", $str );        # �__
   
$str = ereg_replace( chr(ord("�_")), "'", $str );        # �_

   
$unwanted_array = array(    'Š'=>'S', 'š'=>'s', '�_'=>'Z', '�_'=>'z', '�_'=>'A', '�_'=>'A', '�''=>'A', '�_'=>'A', '�"'=>'A', '�:'=>'A', '�+'=>'A', '�+'=>'C', '�_'=>'E', '�%'=>'E',
                               
'�_'=>'E', '�<'=>'E', '�_'=>'I', '�_'=>'I', '�_'=>'I', '�_'=>'I', '�''=>'N', '�''=>'O', '�"'=>'O', '�"'=>'O', '�'=>'O', '�-'=>'O', '�_'=>'O', '�T'=>'U',
                               
'�_'=>'U', '�>'=>'U', '�_'=>'U', '�_'=>'Y', '�_'=>'B', '�_'=>'Ss', 'à'=>'a', 'á'=>'a', 'â'=>'a', '�_'=>'a', 'ä'=>'a', '�_'=>'a', 'æ'=>'a', '�'=>'c',
                               
'è'=>'e', '�c'=>'e', 'ê'=>'e', '�<'=>'e', 'ì'=>'i', '�-'=>'i', '�R'=>'i', 'ï'=>'i', 'ð'=>'o', '�+'=>'n', '�_'=>'o', '�_'=>'o', '�_'=>'o', '��'=>'o',
                               
'�'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', '�>'=>'u', '�_'=>'y', '�_'=>'y', '�_'=>'b', 'ÿ'=>'y' );
   
$str = strtr( $str, $unwanted_array );

   
# Bullets, dashes, and trademarks
   
$str = ereg_replace( chr(149), "&#8226;", $str );    # bullet �_�
   
$str = ereg_replace( chr(150), "&ndash;", $str );    # en dash
   
$str = ereg_replace( chr(151), "&mdash;", $str );    # em dash
   
$str = ereg_replace( chr(153), "&#8482;", $str );    # trademark
   
$str = ereg_replace( chr(169), "&copy;", $str );    # copyright mark
   
$str = ereg_replace( chr(174), "&reg;", $str );        # registration mark

   
return $str;
}
?>
sinfocol at sinfocol dot org
30-Jun-2009 09: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";
    }
?>
glen at glencooper dot com
10-Mar-2009 07:27
Thank you joeldegan for your termcolored function.  I write a lot of command-line scripts using PHP and like to colorize them.  I was having a problem with the termcolored function where the next character echo'ed after calling termcolored() was being dropped.  Turns out you don't need the extra chr(27) at the end of each term color code.

Here's my modified version of your function, renamed to echocolor.

<?php
function echocolor($text,$color="normal",$back=0)
{
 
$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" );
 
$out = $colors["$color"];
 
$ech = chr(27)."$out"."$text".chr(27)."[0m";
  if(
$back)
  {
    return
$ech;
  }
  else
  {
    echo
$ech;
  }
}
?>
voromax
31-Jan-2009 03: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 01: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 04: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 09: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/
markem at airmail dot net
09-Jul-2008 10:34
First, the linefeed versus carriage return confusion:

When typewriters were first invented they were manually moved.  You could do a couple of things with them.  You could type on it (which would move the carriage one space to the left as you typed each character), you could hit the backspace key (which would move the carriage one space to the right), press the line feed button (which would cause the carriage to roll up one line), and return (which would move the carriage all the way to the right again).  When electric typewriters came in to being these functions were made into their electronic counterparts. When terminals appeared they were given the same functions just as word processors, text editors, and everything else that deals with the typed word handles them.

When computers first came out though, the dopey people who invented them wanted to distinguish themselves.  One of the ways they did that was to only use some of the commands.  Which is why the Macintosh originally only used the carriage return command and why Linux/Unix only used the line feed command.  This is why there is "\r" (carriage return), "\l" (Line Feed), and "\n" (OS appropriate).  One of the few things that IBM got right was that it should really be <Carriage Return><Line Feed> and not just one or the other.

So like the reason our roads are a certain width is because that was the width of two horses pulling a Roman chariot, the reason we use these terms is because of the humble non-electronic typewriter and how it worked.

Second - I believe that PHP actually generates ANSI characters and not ASCII characters.  Although there were different extended character sets for the ASCII characters (ie: 128-255), the one depicted on the http://www.asciitable.com/ website clearly shows the IBM standardized ASCII extended table.  (ie: If you ran a BASIC program on your computer you would see the set shown on the above website.)  If, however, you print out the characters via the CHR() function in PHP it prints out the ANSI character set.  (ASCII and ANSI are the same for 0-127.)  Although you can get the characters to print (via Unicode) through the CHR() function - this is still simply showing it is using ANSI and not ASCII.  (Because Unicode is an extension of the ANSI character set and not the ASCII character set.)

If this is so (and my tests show it is) - should the documentation be changed to reflect this?  :-?
Miguel Perez
19-Sep-2007 01:48
This is my implementation of unichr:

<?php
function unichr($c) {
    if (
$c <= 0x7F) {
        return
chr($c);
    } else if (
$c <= 0x7FF) {
        return
chr(0xC0 | $c >> 6) . chr(0x80 | $c & 0x3F);
    } else if (
$c <= 0xFFFF) {
        return
chr(0xE0 | $c >> 12) . chr(0x80 | $c >> 6 & 0x3F)
                                    .
chr(0x80 | $c & 0x3F);
    } else if (
$c <= 0x10FFFF) {
        return
chr(0xF0 | $c >> 18) . chr(0x80 | $c >> 12 & 0x3F)
                                    .
chr(0x80 | $c >> 6 & 0x3F)
                                    .
chr(0x80 | $c & 0x3F);
    } else {
        return
false;
    }
}
?>
darkodemon at gmail dot com
27-Apr-2007 11: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/>';

?>
vdklah at hotmail dot com
27-Apr-2007 09:02
I'm sorry to say that the posted convertIntToAlphabet function does not work correctly. It fails on numbers with a "Z" in it! Aside that it also gives a PHP warning, I really did not like recursion 'cauz huge numbers leads into unneeded memory usage. Here some results showing problems:

Dec    convertIntToAlphabet
...
24    X
25    Y
26        -> empty!
27    AA
28    AB
...
76    BX
77    BY
78        -> empty!
79    CA
80    CB
...
1350    AYX   
1351    AYY   
1352        -> empty!
1353    A    -> bad!
1354    B    -> bad!

So I have written another version:

    function toAlphaNumber( $num )
    {
        $anum = '';
        while( $num >= 1 ) {
            $num = $num - 1;
            $anum = chr(($num % 26)+65).$anum;
            $num = $num / 26;
        }
        return $anum;
    }

With improved results:

Dec    toAlphaNumber
...
24    X
25    Y
26    Z
27    AA
28    AB
...
76    BX
77    BY
78    BZ
79    CA
80    CB
...
1350    AYX
1351    AYY
1352    AYZ
1353    AZA
1354    AZB
lawright at mac dot com
04-Jan-2007 03:39
A little modification of the really useful onlyreadables function posted by jgraef below that saves some of the common characters..

function onlyreadables($string) {
  for ($i=0;$i<strlen($string);$i++) {
    $chr = $string{$i};
    $ord = ord($chr);

    if ($ord>32 and $ord<126)
        continue;
    elseif ($ord>191 and $ord<198)
        $string{$i} = 'A';
    elseif ($ord>199 and $ord<204)
        $string{$i} = 'E';
    elseif ($ord>203 and $ord<208)
        $string{$i} = 'I';
    elseif ($ord>209 and $ord<215)
        $string{$i} = 'O';
    elseif ($ord>216 and $ord<221)
        $string{$i} = 'U';
    elseif ($ord>223 and $ord<230)
        $string{$i} = 'a';
    elseif ($ord>231 and $ord<236)
        $string{$i} = 'e';
    elseif ($ord>235 and $ord<240)
        $string{$i} = 'i';
    elseif ($ord>241 and $ord<247)
        $string{$i} = 'o';
    elseif ($ord>249 and $ord<253)
        $string{$i} = 'u';
    elseif ($ord>252 and $ord<256)
        $string{$i} = 'y';
    elseif ($ord==241)
        $string{$i} = 'n';
    elseif ($ord==209)
        $string{$i} = 'N';
    else
        $string{$i} = '.';
  }
  return $string;
}
Paddy and Ger
02-Jan-2007 01:35
This is just a small piece that allows you to echo out a set number of characters from a string. We were writing option values (html form element) dynamically from an xml file. Some of the strings were too long and as the select tag has no attributes to control the width or columns it seems a handy way to solve the problem.

$string = "this is some text";

$length = strlen($string);   // gets the length of the string

$newLength = -($length - 5);  // makes the length smaller by 5 characters

$string = substr("$string", 0, $newLength);  // sets the string to be 5 characters in length

echo $string;
23-Nov-2006 10:08
I was really surprised to see that work:

$myurl = preg_replace('~%([0-9a-f])([0-9a-f])~ei', 'chr(hexdec("\\1\\2"))', $myurl);

'M%C3%BCnchen' (which is what a Browser makes of an URL containing verbatim utf-8) gives a nice 2-byte-unicode-char: 'M�_nchen'
jgraef at users dot sf dot net
04-Nov-2006 06:15
Hi,

This little function will replace unreadable chars with a "." in your string

function onlyreadables($string) {
  for ($i=0;$i<strlen($string);$i++) {
    $chr = $string{$i};
    $ord = ord($chr);
    if ($ord<32 or $ord>126) {
      $chr = ".";
      $string{$i} = $chr;
    }
  }
  return $string;
}
jasonwiener.com
22-Sep-2006 05:58
In re: to Mike's post on converting int to alpha. 

http://us3.php.net/manual/en/function.chr.php#54256

I'm using it to build an A-Z index and wanted to drive it using ints via a for loop.  The prob was it only produced a-y when i started @ 1 and incremeneted to 27.  Made a couple changes and it works great now.  Thanks Mike for doing the heavy lifting.

J.

---start code---
    function convertIntToAlphabet($int_wert) {
        if($int_wert%27>=1) {
           $alpha_string=chr(($int_wert%27)+64).$alpha_string;
           $alpha_string=convertIntToAlphabet($int_wert/27).$alpha_string;
       }
       return $alpha_string;
    }
---finish code---
jdavid at skynet dot be
05-Sep-2006 11:33
To elaborate on JasonLauDotBiz's piece of code and also schafer at robandger dot com:

for ($i = 0; $i < 10; $i++) {
    $randnum = mt_rand(0,61);
    if ($randnum < 10)
        $randstr .= $randnum;
    else if ($randnum < 36)
        $randstr .= chr($randnum+55);
    else
        $randstr .= chr($randnum+61);
}
echo $randstr;

This will give you a 10 character string consisting of [A-Za-z0-9]. Usefull for passwords or other random strings.
mwgamera at gmail dot com
22-Aug-2006 03: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 03:34
I didn't see it here, so here's simple random string generation using char.

for($i=0; $i<7; $i++){
$random_string .= chr(rand(0,25)+65);
}
echo $random_string;
sgaston at mercy corps dot ()rg
13-Feb-2006 10:52
I found this function useful as a way to detect and to replace Microsoft Smart Quotes when desplaying info on a webpage.

The following lines seem to do the trick:

<?php
$text
= "string containing Microsoft Smart Quotes...";
$chrs = array (chr(150), chr(147), chr(148), chr(146));
$repl = array ("-", "\"", "\"", "'");
$text = str_replace($chrs, $repl, $text);
?>
plugwash at p10link dot net
14-Jan-2006 08:41
bear in mind that php doesn't really care about character sets. php strings are just arbitary byte sequences thier meaning (especailly when you go beyond code 127) depends entirely on whats interpreting the data (in the case of a browser the charset specified in the http headers).
admin at icstrategy dot midgetforhire dot com
08-Jan-2006 06:51
I made a password generator with this function...

<?php
$passlength
= 8;
$pass = "";
$i = 0;
while(
$i <= $passlength)
    {
   
$pass .= chr(rand(33,126));
   
$i++;
    }
echo
$pass;
?>

Ofcourse you can change passlength.

Example of an 8-char password:
AFJ\)t'u}

I realise it isn't compatible for all sites, but most will accept :)
bg at ms dot com
16-Oct-2005 06:20
"If anyone can shed some light on what the difference is, please do."

This is what happens when you give bright young people new power but without old understanding.

A line feed
...........does this.

A carriage return
does this.

The "carriage" is the typewriter (or teletypewriter's) strikehead mechanism.  The "return" means return to leftmost margin; whereas, linefeed means just go down one line but remain at unaltered horizontal position.
php at elijahtech dot com
26-Aug-2005 03:52
Based on Mike's code, here are some handy functions to convert integer numbers into an alphanumeric form based on a custom character set.  Meaning, the array $chrs can include anything, and as long as the same $chrs is used in the decoding, it will always work.  I am using it a condense a generated ID that gets displayed.

e.g., g5 = 997, 10000093 = FXtP -- Much shorter!

Elijah
-----------------------------------------------------------
$chrs = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S' ,'T', 'U', 'V', 'W', 'X', 'Y', 'Z');

function int_to_alph($int, $chrs)
{
  $base = sizeof($chrs);
  do {
    $alph = $chrs[($int % $base)] . $alph;
  } while($int = intval($int / $base));
  return $alph;
}

function alph_to_int($alph, $chrs)
{
  $base = sizeof($chrs);
  for($i = 0, $int = 0; $i < strlen($alph); $i++)
  {
    $int += intval(array_search(substr($alph, strlen($alph) - $i - 1, 1), $chrs)) * pow($base, $i);
  }
  return $int;
}
grey - greywyvern - com
19-Aug-2005 02: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);

?>
Mike
28-Jun-2005 02:43
Hi out there!

Here are two usefull functions to convert ordinal values to int value and back (unlimited length).

For Example:
'A' = 1
'B' = 2
'C' = 3
'AA' = 27
'ABC' = 731

Convert ordinal value to INT:

function convertAlphabetToInt($alpha_string) {
    $int_wert=0;
    $potenzcounter=0;
    for ($i=strlen($alpha_string);$i>0;$i--) {
        $ordinalwert=(ord(substr($alpha_string,$i-1,1))-64);
        $int_wert+=$ordinalwert*pow(26,$potenzcounter);
        $potenzcounter++;
    }
    return $int_wert;
}

And back from INT to ordinal:

function convertIntToAlphabet($int_wert) {
    if($int_wert%26>=1) {
        $alpha_string=chr(($int_wert%26)+64).$alpha_string;
        $alpha_string=convertIntToAlphabet($int_wert/26).$alpha_string;
    }
    return $alpha_string;
}

This functions will return for example:
convertAlphabetToInt("ABCD") => Output: 19010
convertIntToAlphabet(19010) = Output: "ABCD"

I hope someone can use it :)
Greetings,
Mike
24-May-2005 02:15
If you want to increment your letter, which is stored as a string, you have to convert it back to an integer first.

<?php
    $letter
=strtolower($_GET['letter']);    //You wanted this originally, but not decided you want the previous letter
   
$letter=ord($letter);            //Convert to an integer
   
$letter=chr($letter-1);            //Convert back to a string, but the previous letter (naturally won't work with A or a)
?>
mike at go dot online dot pt
11-Mar-2005 08: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 12: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 06: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 11: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 06: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
14-May-2004 02: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 09: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 11: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
06-Apr-2004 12: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
26-Mar-2004 12: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 08: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 05:20
Lowercase alphabet:
for($a=97;$a<(97+26);$a++){ echo chr($a); }
infoserv at chollian dot net
25-Jun-2003 03: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
27-Mar-2003 02: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 09:26
I usally used this code to test a Chinese string:

<?php
$chinese_str
= "_�_R��";
if (
preg_match("/^[".chr(0xa1)."-".chr(0xff)."_-]+$/",$chinese_str) {
    echo
'This is a Chinese word..';
} else {
    echo
'This is not a Chinese word..';
}
?>
Kristin
07-Mar-2003 04: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 10: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
09-Nov-2002 12: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
29-Jun-2002 03: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 07: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 03: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 11: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.
 

 
credits | contact