dongpaozhi5734 2014-09-04 17:48
浏览 261
已采纳

PHP每隔4个字符添加一个空格,但是当你到达逗号时忽略它

This is my line

AQUA19097444,AQUA43188766,AQUA49556282,AQUA51389151,AQUA57267110,BLUE12811521,BLUE15966728

This is what I want to achieve in the end

AQUA 1909 7444,AQUA 4318 8766,AQUA 4955 6282,AQUA 5138 9151,AQUA 5726 7110,BLUE 1281 1521,BLUE 1596 6728

Notice there is space every 4 characters but does not include a space if a comma is next.

This is what I have tried so far: note I am in a for each loop

$Raffles[$index] = chunk_split($Raffles[$index], 4, ' ');

This is the output of the code

AQUA 1909 7444 ,AQU A431 8876 6,AQ UA49 5562 82,A QUA5 1389 151, AQUA 5726 7110 ,BLU E128 1152 1,BL UE15 9667 28

As you can see it does a space when It reaches the comma which I want it to ignore

Please help me out and thank you for reading my question.

  • 写回答

3条回答 默认 最新

  • drbd65446 2014-09-04 17:52
    关注

    Explode your string, then loop through it and use chunk_split to place the space every fourth character.

    $string = 'AQUA19097444,AQUA43188766,AQUA49556282,AQUA51389151,AQUA57267110,BLUE12811521,BLUE15966728';
    
    $exploded_string = explode(',', $string);
    
    foreach($exploded_string as $item){
        $result[] = chunk_split($item, 4, ' ');
    }
    

    print_r($result); will give you

    Array ( [0] => AQUA 1909 7444 
            [1] => AQUA 4318 8766 
            [2] => AQUA 4955 6282 
            [3] => AQUA 5138 9151 
            [4] => AQUA 5726 7110 
            [5] => BLUE 1281 1521 
            [6] => BLUE 1596 6728 )
    

    If you want to convert this back into a comma separated string use $result = implode(',', $result);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛