dongshuobei1037 2016-04-25 17:28
浏览 36

正则表达式子串的长度

I receive a string conformed by numbers and points. I need those numbers to have a minimum length of 3, so, I have to add one or more zeros in from of the numbers with a lower length.

Example:

If I have:

233.14.205.1.194056.270132

I need it to be:

233.014.205.001.194056.270132
    ↑       ↑↑

(Note the 014 where there was a 14 and the 001 where there was a 1)

I know I can explode the string, add the zeros I need and implode it again, but I want not to create a function for something that can solved with a native function (preg_replace) and I am not very good with regex (yet).

  • 写回答

3条回答 默认 最新

  • doushui5587 2016-04-25 17:40
    关注

    Using explode -> zero padding -> implode will indeed be straight forward.

    Since you're specifically asking for preg_replace way of doing it here it is:

    $s = '233.14.205.1.194056.270132'
    
    $repl = preg_replace(array('/\b\d\b/', '/\b\d\d\b/'), array('00$0', '0$0'), $s);
    //=> 233.014.205.001.194056.270132
    

    Here we're passing a 2 element array of regex to preg_replace and inserting singe or double zeroes before the matched double/single digit.

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致