Writing PHP code without special characters

2

Is there a way to print special characters in PHP using just the code with ascii characters?

For example, in javascript we can use \ u00e1 in the middle of the text. In Java, we can use \ u2202 for example.

What about PHP? How can I use it?

I do not want to include special characters in my code.

    
asked by anonymous 23.04.2018 / 23:18

1 answer

4

What's new in PHP7:

Exists syntax for escaping Unicode code, 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";

It will be printed as:

á
∂
ª
ª
香

Example in ideone: link

  

Note 1: \n is only for line break only to separate echo s, in HTML use <br>

     

Note 2: Only double quotes support this, single quotation marks so echo '\u{aa}'; will not work

PHP5 escape syntax

In PHP before 7 (ie 5) this syntax existed (and still exists):

\x[0-9A-Fa-f]{1,2}

That uses hexadecimal notation and is limited to 1 or 2 digits after \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 \x (since unicode characters are formed like this), for example \xc3\xa1 would equal \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 chr(...) function or even sprintf(...) ), for example: < printf(...) / p>

<?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 the ideone: link

    
24.04.2018 / 00:29