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

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

报告相同问题?

悬赏问题

  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥200 求能开发抖音自动回复卡片的软件
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。