douwen2072 2018-11-15 16:42
浏览 37
已采纳

在某些字符串之前删除空格

I can think of "foreach string replace" ways of doing this but feel that a regex replace method would be faster and more elegant, unfortunately regex is not my strongest thing.

I want to take a string like this

23 AB 5400 DE 68 RG

and turn it into

23AB 5400DE 68RG

The number of spaces between the digits and following letters is USUALLY one but could be variable.

I have this example, that is working to find the groups but how do I get rid of the spaces in the replacement?

https://regex101.com/r/ODhpQM/2

This is the code generated by my attempt

$re = '/(\d+ +)(AB|DE|RG|DU)/m';
$str = '23 AB 5400 DE 68 RG
        33 DU 88 DE 8723 AB
        55    RG 76  AB  92 DE';
$subst = '\\1\\2';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;
  • 写回答

5条回答 默认 最新

  • dougeqiang1619 2018-11-15 17:16
    关注

    Unless I'm missing something, it seems like it would be fine to disregard the digits and just replace any non-digits with spaces before them with the same text without the spaces.

    $result = preg_replace('/\s+(\D+)/', '$1', $string);
    

    i.e. match anything like " AB" and replace it with "AB".

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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路