PHP conditional string replacement str_replace

谁都会走 提交于 2019-12-21 20:57:04

问题


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.



来源:https://stackoverflow.com/questions/10941490/php-conditional-string-replacement-str-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!