2

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);
    }

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

No need to put a negative lookahead here: (?!:)\s, a white-space can't be a colon.
@CasimiretHippolyte you are right..my fault..i wrote the lookahead part in starting and then added the \w part and messed it up..
1

The following regex might work for you:

/(?<!:)(?= \d)/g

With replacement: :

$output = preg_replace('/(?<!:)(?= \d)/', ':', $input);

It matches a position that is followed before space and digit (?= \d) and not preceded by a colon (?<!:). That's why the replacement group can be a colon only.

This is called lookarounds. Here be both use a positive lookahead (?=...) and a negative lookbehind: (?<!...).

https://www.regex101.com/r/oH7cI3/1

Comments

1

Use lookarounds:

(?<=[a-z]) # a-z behind
\          # a space
(?=\d)     # a digit ahead

See a demo on regex101.com and replace the occurences with a colon.

Comments

0
$string="width: 40cm height: 70cm";

$temp=exploade(" ",$string);

foreach($temp as $value){

if(strstr($value,'width') && strstr($value,'height')){
    $new_temp[]=$value.":";
}else{
    $new_temp[]=$value;
}

} $new_string=implode(" ", $new_temp);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.