dongmubei7950 2012-06-17 14:45
浏览 59
已采纳

PHP:用硬替换空间替换数字之间空格的正则表达式

I would like to create a regular expression that will replace a normal space with hard-breaking space according to my country typographical rules. It shouldn't touch HTML tags.

All spaces in these examples should be hard-breaking:

Numbers

1 000
10 000
100 000
1 000 000
etc..

Dates

17. 6.
17. 6. 2012

I came up with:

$pattern = '/((\d\.?)\s(\d))(?=[^>]*(<|$))/';
$text = preg_replace($pattern, '$2&nbsp;$3', $text);

It can do all of these but: 17. 6. 2012 It won't replace the second space, so result is ->

17.&nbsp;6. 2012

Thank you for any help!

  • 写回答

2条回答 默认 最新

  • duandan5471 2012-06-17 15:21
    关注

    The (\d) is eating the first trailing digit, and if the trailing number only has a single digit, there won't be enough of it left to match on the next pass.

    For instance, the following work fine: 12 34 56, 12. 34. 56. But these do not: 1 2 3, 1. 2. 3

    The (\d) can be moved into the lookahead, to avoid eating it:

    $pattern = '/((\d\.?)\s)(?=\d[^>]*(<|$))/';
    $text = preg_replace($pattern, '$2&nbsp;$3', $text);
    

    Combining this with @flec's use of a lookbehind yields:

    $pattern = '/(?<=\d)(\.?)\s(?=\d[^>]*(<|$))/';
    $text = preg_replace($pattern, '$1&nbsp;', $text);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!