使用PHP使用SPACE分隔符将十进制转换为ASCII

时间:2016-03-06 03:06:37

标签: php decimal ascii chr

使用PHP,如何将一个带有空格的十进制数字串转换为一个没有空格的字符串?(当然除非转换为DEC空格(32))

示例:84 104 97 110 107 32 121 111 117

我已经检查了相关问题,其中大多数只是询问内置函数将十进制转换为ascii。我知道chr()和ord(),我认为解决方案确实应该使用explode()和implode()以及字符串替换。我对for和foreach循环感到非常恐怖,所以这种逻辑打破了我的想法。 :)

我找到的最接近的SO主题是这个与我要求的基本相反的主题 - Using PHP to Convert ASCII Character to Decimal Equivalent

1 个答案:

答案 0 :(得分:1)

这可能是strtok函数实际上可用于某事的情况。

strtok函数根据字符标记字符串。在这种情况下,令牌定界符是一个空格。每次调用strtok时,它都会返回字符串中的下一个标记。

chr函数用于将序数(十进制)数转换为等效的ASCII字符。

function myParseString($str) {
    $output = ''; // What we will return
    $token = strtok($str, ' '); // Initialize the tokenizer

    // Loop until there are no more tokens left
    while ($token !== false) {
        $output .= chr($token); // Add the token to the output
        $token = strtok(' '); // Advance the tokenizer, getting the next token
    }
    // All the tokens have been consumed, return the result!
    return $output;
}
$str = '84 104 97 110 107 32 121 111 117';
echo myParseString($str);

(欢迎你。)