如何在没有 ord() 的情况下在 PHP 中将字符串转换为 ASCII 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42398502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a string to ASCII value in PHP without ord()?
提问by Rani
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()
?
我正在寻找在 php 中将字符串 say 'Hello' world 转换为它的 ASCII 值。但我不想使用ord()
. 是否有任何其他解决方案可以在不使用的情况下打印 ascii 值ord()
?
回答by user3942918
Unpacks from a binary string into an array according to the given format.
根据给定的格式将二进制字符串解包为数组。
Use the formatC*
to return everything as what you'd get from ord()
.
使用该格式C*
将所有内容作为您从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
)
回答by Purple Lady
You could try the iconv
native function:
您可以尝试本iconv
机功能:
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
回答by Gavin Hymanson
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 65if 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.
您可以迭代字符串中的每个字符,使用 say strpos找到它在字典字符串中的偏移量,然后添加一个基数,例如65如果您的字典以“ ABC
开头...
您需要处理未找到的字符,所以也许最好使用“ #ABC...然后添加一个基数64的字典,显然你需要测试“#”作为一个特殊字符。
您甚至可以针对有限字符集“ #A..Z”、“ #a..z”、“ #0..9”的
多个字典字符串进行测试,
您明白了,但不知道为什么要限制自己我能够'