What’s new in PHP7:
There is support for Unicode code escape syntax, for example:
<?php
echo "\u{00e1}\n";
echo "\u{2202}\n";
echo "\u{aa}\n";
echo "\u{0000aa}\n"; //o mesmo que o anterior mas com zeros a esquerda
echo "\u{9999}\n";
Will be printed as:
á
∂
ª
ª
香
Example in the ideone: https://ideone.com/2Tcsed
Note 1: The \n
is only for line breaking is just to separate the echo
s, in HTML use <br>
Note 2: Only double quotes support this, single quotes like this echo '\u{aa}';
won’t work
Escape syntax in PHP5
In PHP before 7 (ie 5) there was (and still exists) this syntax:
\x[0-9A-Fa-f]{1,2}
That uses hexadecimal notation and is limited to 1 or 2 digits after the \x
and just like Unicode (\u{[0-9A-Fa-f]+}
) should also be used in double quote notations.
Then to write a Unicode character it will be necessary to use two or more times the \x
(since single characters are formed like this), for example \xc3\xa1
would amount to \u{00e1}
, example both print á
:
<?php
echo "\xc3\xa1\n";
echo "\u{00e1}\n";
Comparing both:
if ("\xc3\xa1" === "\u{00e1}") {
echo 'São iguais';
} else {
echo 'São diferentes';
}
Will display São iguais
Alternative
There is also the function chr(...)
or even sprintf(...)
(or even with printf(...)
), for example:
<?php
$caracterChr = chr(27);
$caracterPrintf = sprintf('%c', 27);
var_dump($caracterChr, $caracterPrintf);
Comparing both:
if ($caracterChr === $caracterPrintf) {
echo 'São iguais';
} else {
echo 'São diferentes';
}
See the example in ideone: https://ideone.com/FJnGJp
You want to know how to print characters ?
– Isac
In addition to Guilherme’s answer, you can use Chr( ) to represent any byte (or sequence of them, concatenating) by making the combination you want.
– Bacco