mnfst
mnfst

Reputation: 71

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

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.

Upvotes: 0

Views: 1189

Answers (3)

mamal
mamal

Reputation: 1986

try this :

$input = "old iccid : 809831 3245 345 new iccid : 999000 112221"
$output = preg_replace("/(\d)\s+(\d)/", "$1$2", $input);
echo $input . "\n" . $output; //old iccid : 8098313245345 new iccid : 999000112221

Upvotes: 0

mickmackusa
mickmackusa

Reputation: 47992

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.

Upvotes: 0

xdazz
xdazz

Reputation: 160883

Try:

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

Upvotes: 2

Related Questions