13

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()?

2
  • 3
    Why wouldn't you use ord? Commented Feb 22, 2017 at 17:37
  • 1
    That's like saying I want to go out in the rain and don't want to get wet but I don't want to use an umbrella.. A PHP native function exists to solve your problem perfectly, but you'd rather write something from scratch? Commented Feb 22, 2017 at 17:44

3 Answers 3

35

unpack()

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

nice, I like that
And you can further use implode to combine the array values to a string like this: implode('', unpack("C*", "Hello world")) returns 7210110810811132119111114108100
1

You 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

0

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

I wonder why this 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.