PHP 条件字符串替换 str_replace [英] PHP conditional string replacement str_replace
本文介绍了PHP 条件字符串替换 str_replace的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我试图用-"替换单词之间的空格的字符串.
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);
我想使用 str_replace 函数实现的是:
What i want to achieve, using the str_replace function, is:
"Color-red, Color-blue, Color-black";
但这会返回:
"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 ,
.
preg_replace("/(?<!,)\s/", '-', $mystring);
这篇关于PHP 条件字符串替换 str_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文