regexp在逗号后添加空格,但当逗号是千分隔符时不添加空格


regexp add space after comma but not when comma is thousands separator?

以一种简单的方式使用php regexp,是否可以修改字符串,在单词后面的逗号和句点后面添加空格,但不能在逗号或句点前面和后面加数字(如1000.00)之后添加空格?

String,looks like this with an amount of 1,000.00

需要更改为…

String, looks like this with an amount of 1,000.00

当然,这应该允许多个实例。。。这是我现在使用的,但它导致数字返回为1000。00

$punctuation = ',.;:';
$string = preg_replace('/(['.$punctuation.'])['s]*/', ''1 ', $string);

您可以用', '替换'/(?<!'d),|,(?!'d{3})/'

类似于:

$str = preg_replace('/(?<!'d),|,(?!'d{3})/', ', ', $str);

我在搜索这个正则表达式。

这个帖子真的帮助了我,我改进了Qtax提出的解决方案。

这是我的:

$ponctuations = array(','=>', ',''.'=>'. ',';'=>'; ',':'=>': ');
foreach($ponctuations as $ponctuation => $replace){
    $string = preg_replace('/(?<!'d)'.$ponctuation.'(?!'s)|'.$ponctuation.'(?!('d|'s))/', $replace, $string);
}

有了这个解决方案,"像这样的句子:this"将不会更改为"像那样的句子:  this"(whith 2 blank space)

仅此而已。

虽然这已经很老了,但我一直在寻找同一个问题,在理解了给出的解决方案后,我有了不同的答案。

此正则表达式不检查逗号前的字符,而是检查逗号后的字符,因此可以将其限制为字母字符。此外,这不会创建逗号后有两个空格的字符串。

$punctuation = ',.;:';
$string = preg_replace("/([$punctuation])([a-z])/i",''1 '2', $string);

测试脚本可以在这里检查。