I am looking to convert a string say 'Hello' world to its ASCII value in php.
But I don't want to use ord(). Are there any other solutions for printing ascii value without using ord()?
3 Answers
Unpacks from a binary string into an array according to the given format.
Use the format C* to return everything as what you'd get from ord().
print_r(unpack("C*", "Hello world"));
Array
(
[1] => 72
[2] => 101
[3] => 108
[4] => 108
[5] => 111
[6] => 32
[7] => 119
[8] => 111
[9] => 114
[10] => 108
[11] => 100
)
2 Comments
implode to combine the array values to a string like this: implode('', unpack("C*", "Hello world")) returns 7210110810811132119111114108100You could iterate over each character in the string, find its offset into a dictionary string using say strpos, then add on a base number eg 65 if your dictionary started with "ABC...
You'd need to handle unfound characters, so maybe better to use a dictionary of "#ABC... then add a base of 64, obviously you'd need to test for "#" as a special character then.
You could even test against multiple distionary strings for limited character sets "#A..Z", "#a..z", "#0..9"
You get the idea, but without knowing why you want to limit yourself I can't tell whther this is useful to you.
Comments
You could try the iconv native function:
string iconv ( string $in_charset , string $out_charset , string $str )
So it would be:
<?php
$string = "This is the Euro symbol '€'.";
echo iconv("UTF-8", "ASCII", $string), PHP_EOL;
?>
Taken from: http://php.net/manual/en/function.iconv.php
1 Comment
iconv() function allows any unicode character to slip through. Take any unicode character and you'll see that it passes through, even when using iconv('UTF-8', 'ASCII//IGNORE', $string)
ord?