How to convert a string to ASCII value in PHP without ord()?

ⅰ亾dé卋堺 提交于 2019-12-22 07:53:04

问题


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


回答1:


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
)



回答2:


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", $text), PHP_EOL;

?>

Taken from: http://php.net/manual/en/function.iconv.php




回答3:


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.



来源:https://stackoverflow.com/questions/42398502/how-to-convert-a-string-to-ascii-value-in-php-without-ord

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!