我想用"Some Sentence,[Space]Some Sentine"替换字符串中的"Some Pentence,Some Sension"。
我尝试了str_replace(",", ", ",$str)
,但问题是它同时替换了","answers",[Space]"正在创建",[Space]"answers",[Space][Space]"。有没有办法只替换两个句子之间的逗号?
我希望你明白我的意思。
您可以这样做:
$string = 'Some Sentence,Some Sentence don''t touch, this one but,thisone do, also';
echo preg_replace('~,([^'s])~', ', $1', $string);
也就是说,找到一个没有空格的逗号,
作为下一个字符[^'s]
。[]
是一个列出字符的字符类,而^
使其成为否定搜索。~
是分隔符,用于指示正则表达式的起始和结束位置。
更新:()
捕获非空白字符,并将其与,
和空格一起返回。
's
是任何空白字符(制表符、换行符、空格(。如果您只需要空间,请将其更改为'h
,这是一个水平空间。
Regex101演示:https://regex101.com/r/eU1iR1/2
更新:
另一种方法:
$string = 'Some Sentence,Some Sentence don''t touch, this one but,thisone do, also';
echo preg_replace('~,'s(*SKIP)(*FAIL)|,~', ', ', $string);
它说,如果它找到一个带有空格的逗号,首先跳过它,否则就添加带有空格的逗点。这是一篇关于这种方法的文章,http://www.rexegg.com/regex-best-trick.html.
演示:https://regex101.com/r/eG8jS8/1
如果分隔符是一致的,您也可以利用字符串操作:
$foo = "Something,Something";
$bar = implode(", ", explode(",", $foo));
explode
使用分隔符作为标记创建一个数组。implode
使用新的分隔符将其连接回来。
注意:这将不考虑空格(和其他字符(很重要的场景。但这是一个简单的选择
另一种方法是这样做:
$str = str_replace(", ", ",", $str);
$str = str_replace(",", ", ",$str);
虽然regex解决方案更强大(它适用于无限空间(,但这个可能更适合新手。
或者,在用,
:替换,
之后的字符之前,您可以使用负向前看来检查它是否不是空白字符
$str = "begin,space, no sp, not space,space,,~~~,@@##$,end";
$str = preg_replace('/,(?!'s)/', ", ", $str);
输出:begin, space, no sp, not space, space, , ~~~, @@##$, end
regex101上的演示