【问题标题】:regexp add space after comma but not when comma is thousands separator?正则表达式在逗号后添加空格,但当逗号是千位分隔符时不添加空格?
【发布时间】:2012-08-26 01:02:17
【问题描述】:

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

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

需要改成...

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

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

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

【问题讨论】:

    标签: php regex punctuation


    【解决方案1】:

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

    类似:

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

    【讨论】:

    • 这真的很接近我正在寻找的东西......你将如何修改它以在我提供的代码示例中使用我的 $punctuation 变量?谢谢
    • $str = preg_replace('/(?&lt;!\d)['.$punctuation.']|['.$punctuation.'](?!\d{3})/', '$0 ', $str);
    【解决方案2】:

    我正在寻找这个正则表达式。

    这篇文章对我很有帮助,我改进了 Qtax 提出的解决方案。

    这是我的:

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

    使用此解决方案,“sentence like: this”不会更改为“sentence like:  this”(带有 2 个空格)

    就是这样。

    【讨论】:

      【解决方案3】:

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

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

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

      测试脚本可以查看here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-08
        相关资源
        最近更新 更多