CancelImage Upload

How to convert a whole string into ASCII code format in PHP

Previously I have discussed how rare symbols can be encoded and decoded from or into ASCII with the PHP functions html_entity_decode and htmlentities(). And while the function htmlentities() is perfect for converting non standard symbols into their ASCII equivalents, it does not convert every symbol out there.

Here then we have to find another workaround, especially if every symbol is to be converted, including regular up and lowercase alphabetic letters. The function that will come to our rescue in this case is ord(), a function that returns the ASCII value of a number.

Ord() will not convert our symbols into HTML friendly ASCII codes as such. We will have to add the &# and ; ourselves. However this does not require to much effort, since as programmers most of us have mastered the loop a long, long time ago.

Something else that needs to be taken into account when working with ord() is that it only ever converts the first symbol of a string. Therefore in order to convert an entire text we need to perform the conversion one symbol at a time. Here is how it is done:


$string ="This is an example string with a few specialy symbols: *?%&/äö$ü!";

for($i = 0; $i != strlen($string); $i++)

     $asciiString .= "&#".ord($string[$i]).";";


$asciiCode = str_replace("&", "&amp;", $asciiString);

echo "String in ASCII:<br>";

echo $asciiString;

echo "<br>The code:<br>";

echo $asciiCode;


Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •