Jacob Raccuia Jacob Raccuia - 5 months ago 10
PHP Question

modify string if specific regex matches

Working in PHP, I have the following mock string.

"width 40cm height 70cm"


If the string does not contain a colon and does have a space followed by a number, I want to add a colon before that space.

The end result I'm looking for is:

"width: 40cm height: 70cm"


I tried a bunch of ways with regex and splitting the string at the match to add the colon, but it was removing the match string. Here is my attempt.

if(strpos($s, ':') === false) {
$array = preg_split('/([0-9])/', $s, -1, PREG_SPLIT_NO_EMPTY);
$array[0] = trim($array[0]) . ':';
$s = implode('', $array);
}

Answer

I think this will work

(\w+)(?=\s+\d)
     <------->
     Lookahead to match
     space followed by 
     digits

Regex Demo

PHP Code

$re = "/(\\w+)(?=\\s+\\d)/m"; 
$str = "width 40cm height 70cm\nwidth: 40cm height 70cm"; 

$result = preg_replace($re, "$1:", $str);
print_r($result);

Ideone Demo

Comments