douke9545 2014-07-04 14:26
浏览 102
已采纳

使用正则表达式删除数字分隔符

I'm looking for a simple stupid solution, to remove delimiters from numbers within strings.

This function replaces 2.000 BC with 2000 BC:

$text preg_replace("/^[0-9.]+$/", "", $text);

Example:

$text = 'Lorem ipsum dolor. Consetetur elitr 2.000 BC sed diam nonumy 300.'

// Current behaviour (the delimeter at the end ot the line disappears):
// Lorem ipsum dolor. Consetetur elitr 2000 BC sed diam nonumy 300

// Expected behaviour:
// Lorem ipsum dolor. Consetetur elitr 2000 BC sed diam nonumy 300.
  • 写回答

2条回答 默认 最新

  • dongxie559554 2014-07-04 14:31
    关注

    You can replace (?<=\d)\.(?=\d) with nothing:

    <?php
    
    $text = 'Lorem ipsum dolor. Consetetur elitr 2.000 BC sed diam nonumy 300.';
    
    $text = preg_replace('/(?<=\d)\.(?=\d)/', '', $text);
    
    var_dump($text);
    
    //string(64) "Lorem ipsum dolor. Consetetur elitr 2000 BC sed diam nonumy 300."
    

    DEMO

    Regex autopsy:

    Regular expression visualization

    • (?<=\d) - a positive lookbehind matching a digit (this will not be replaced) - essentially this requires the . to be preceeded by a digit
    • \. - a literal . character, escaped as . means "any character" in regex
    • (?<=\d) - a positive lookahead matching a digit (this will not be replaced) - essentially this requires the . to be followed by a digit
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器