douzhongjian0752 2014-12-08 23:16
浏览 59
已采纳

正则表达式从IPv4八位字节修剪前导零

I am using the following regex in a PHP script to collect IPv4 Addresses and to also perform some validation of the IPv4 addresses.

A txt file of IPs is read into an array with a file() command, then a foreach loop using preg_match and this regex matches the IPv4 addresses.

However, it currently includes any leading zeros before each octet.

Is it possible to improve this regex to trim any leading zeros in each octet without completely discarding IPs with leading zeros? I would prefer to do this in a single regex instead of adding an additional function to clear the leading zeros.

/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/

Correct output:

38.10.125.242
38.1.1.24

Incorrect output:

038.010.125.242
038.001.001.024

I have been using Lumadis.be to test, but none of the regexes that I tried from other answers in Stack Overflow seem to work?.

  • 写回答

2条回答 默认 最新

  • doujiang1993 2014-12-09 00:42
    关注

    Simpler is just:

    preg_replace('/\b0+/', '', $str);
    

    Since we know the only word boundaries are at the . and the start/end of line

    Edit: it looks like we need a lookahead to avoid empty octets

    preg_replace('/\b0+(?=\d)/', '', $str)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?