php - modify string if specific regex matches -


working in php, have following mock string.

"width 40cm height 70cm" 

if string not contain colon , have space followed number, want add colon before space.

the end result i'm looking is:

"width: 40cm height: 70cm" 

i tried bunch of ways regex , splitting string @ match add colon, removing match string. here attempt.

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

i think work

(\w+)(?=\s+\d)      <------->      lookahead match      space followed       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

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -