【问题标题】:php preg_replace remove thousand separator in a stringphp preg_replace 删除字符串中的千位分隔符
【发布时间】:2013-04-19 16:57:18
【问题描述】:

有一篇长文,我只想去掉thousand separator,不是逗号。

$str = "Last month's income is 1,022 yuan, not too bad.";
//=>Last month's income is 1022 yuan, not too bad.

preg_replace('#(\d)\,(\d)#i','???',$str);

如何编写正则表达式模式?谢谢

【问题讨论】:

  • 请注意,如果用户在列表中犯了一个愚蠢的错误,您可能会遇到问题:He did it 1,2 and 3 times(缺少空格 - 它会变成 12 和 3 次)。

标签: php regex


【解决方案1】:

如果简化规则“匹配任何直接位于数字之间的逗号”对您来说足够好,那么

preg_replace('/(?<=\d),(?=\d)/','',$str);

应该这样做。

您可以通过确保紧跟三个数字来改进它:

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

【讨论】:

    【解决方案2】:

    如果您查看preg_replace documentation,您会发现您可以使用$n 将捕获写回替换字符串中:

    preg_replace('#(\d),(\d)#','$1$2',$str);
    

    请注意,无需转义逗号,或使用i(因为模式中没有字母)。

    另一种(可能更有效)的方法是使用lookarounds。这些不包含在匹配中,因此不必回写:

    preg_replace('#(?<=\d),(?=\d)#','',$str);
    

    【讨论】:

      【解决方案3】:

      第一个(\d)$1 表示,第二个(\d)$2 表示。因此解决方案是使用这样的东西:

      preg_replace('#(\d)\,(\d)#','$1$2',$str);
      

      实际上最好在逗号后面加上 3 个数字,以避免对数字列表造成破坏:

      preg_replace('#(\d)\,(\d{3})#','$1$2',$str);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多