how to define regex (preg_replace) to removes space between number character

人盡茶涼 提交于 2020-05-09 10:53:17

问题


I have string like this:

$str = "old iccid : 809831 3245 345 new iccid : 999000 112221"

How to define regex in order to remove the space character between number character in PHP, to become this output?

$output = "old iccid : 8098313245345 new iccid : 999000112221";

i've tried to use this syntax:

$output = preg_replace( '/\d[ *]\d/', '', $str);

but didn't work well.


回答1:


Try:

$output = preg_replace('/(?<=\d)\s+(?=\d)/', '', $str);



回答2:


The regex engine can traverse the string faster / with fewer steps without the lookbehind.

171 steps: (Demo)

/(?<=\d)\s+(?=\d)/

115 steps (Demo)

/\d\K\s+(?=\d)/

You see, while using the lookaround, the regex engine has to look 1 or 2 ways at every occurrence of a space.

By checking for a digit followed by a space, the regex engine ONLY has to look ahead once it has found the qualifying two-character sequence.

In many cases, lookarounds and capture groups endup costing extra "steps", so I prefer to seek out more efficient alternative patterns.

FYI, the \K "restarts the full string match". In other words, it matches then forgets all characters up to the position of the metacharacter.

p.s. You could also use /\d\K\s+(\d)/ to get the steps down to 106 Demo but then you'd need reference the capture group and my personal preference is to avoid that syntax in the replacement.



来源:https://stackoverflow.com/questions/12345265/how-to-define-regex-preg-replace-to-removes-space-between-number-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!