dongzang7182 2016-03-06 03:06
浏览 108
已采纳

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

Using PHP, how do you convert a string of decimal numbers with spaces in between into a string without spaces? (unless of course it is a DEC space (32) converted)

Example: 84 104 97 110 107 32 121 111 117

I have checked out the related questions and most of them are just asking what the built in function is for converting decimal to ascii. I know chr() and ord() and I think the solution really should use explode() and implode() along with a string replace. I am just horrible at for and foreach loops so the logic breaks my mind. :)

The closest SO topic I found is this one which is basically the opposite of what I am asking for - Using PHP to Convert ASCII Character to Decimal Equivalent

  • 写回答

1条回答 默认 最新

  • doujiaozhan2413 2016-03-06 03:23
    关注

    This would be a situation where the strtok function actually could be used for something.

    The strtok function tokenizes a string based on a character. In this case the token delimiter is a space. Each time you call strtok it returns the next token in the string.

    The chr function is used to convert the ordinal (decimal) number to its ASCII character equivalent.

    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);
    

    (And you are welcome.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形