如何在没有空格的情况下替换所有逗号,而不是用逗号替换空格?

时间:2012-09-16 08:45:31

标签: php regex string preg-replace preg-match

就像,如果这个问题标题的第二部分不存在,我本可以这样做:

$string = 'Hello,this is my string.';
$replacedstring = str_replace(',', ', ', $string);

但如果用户确实正确格式化了句子,如Hello, this is my string.中所示。那么这会导致它变成Hello, this is my string.,这是我不想要的。

那么,我如何在PHP中使用preg_replace和类似的正则表达式函数呢?

4 个答案:

答案 0 :(得分:7)

$replaced_string = preg_replace("/,([^\s])/", ", $1", $str);

我会用这个。

答案 1 :(得分:2)

使用此:

$ret = preg_replace('/(?<=\S,)(?=\S)/', ' ', $string);

答案 2 :(得分:0)

您可以使用

str_replace(array(', ', ','), ', ', $string);

是多余的,因为将,替换为,,但可能更高效的是正则表达式或任何其他不太大的文本算法

答案 3 :(得分:0)

$string = 'Hello,this is my string, sir.';
$pattern = '/,([^ ])/'; # every comma that is followed by anything but space
$replacement = ', ';
echo preg_replace($pattern, $replacement, $string);