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?
(?<!,)\s
That uses a negative lookbehind to match all spaces (
\s
) that aren't followed by a,
.Play with the regex here.