How to use preg_replace

2019-09-01 08:43发布

问题:

I have a String:

    $str= "(and marque:'Mercedes Benz' model:'F Type')";

I want to return string like this:

    $str2= "(and marque:'Mercedes-Benz' model:'F-Type')";

so, I want to replace space with '-' char but only between '' chars.

Should I use preg_replace function?

回答1:

How about:

$str= "(and marque:'Mercedes Benz' model:'F Type')";
$str = preg_replace("/'(\w+)\s+/","'$1-", $str);
echo $str,"\n";

output:

(and marque:'Mercedes-Benz' model:'F-Type')