Jacob Raccuia Jacob Raccuia - 2 years ago 70
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 Source

I think this will work

     Lookahead to match
     space followed by 

Regex Demo

PHP Code

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

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

Ideone Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download