PHP conditional string replacement str_replace

2019-04-13 14:16发布

问题:

This is the string i'm trying to replace white spaces between the words with "-".

$mystring = "Color red, Color blue, Color black";
$newstring = str_replace(' ', '-', $mystring);

What i want to achieve, using the str_replace function, is:

"Color-red, Color-blue, Color-black";

But that returns:

"Color-red,-Color-blue,-Color-black";

I guess i need a condition that replaces white spaces "not after the comma" or "between two words". But i have no idea. Any suggestion?

回答1:

(?<!,)\s

That uses a negative lookbehind to match all spaces (\s) that aren't followed by a ,.

preg_replace("/(?<!,)\s/", '-', $mystring);

Play with the regex here.