PHP conditional string replacement str_replace

2019-04-13 14:41发布

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条回答
该账号已被封号
2楼-- · 2019-04-13 15:06

(?<!,)\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.

查看更多
登录 后发表回答