Reputation: 177
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?
Upvotes: 2
Views: 1306
Reputation: 2698
(?<!,)\s
That uses a negative lookbehind to match all spaces (\s
) that aren't followed by a ,
.
preg_replace("/(?<!,)\s/", '-', $mystring);
Upvotes: 4