duanbi7247 2013-11-05 17:10
浏览 83
已采纳

PHP如何从字符串中提取3位数并输出它

This is a bit a strange issue. I am trying just to get sequential 3 digit integer from a string.

Now I thought I was successfully doing it using this code below...

preg_match_all('!\d+!', $image['title'], $integer); echo $integer[0][2];

But now it seems to be failing on some strings.

It works fine on these strings...

  1. TZR9000 Supertroop 2014 001
  2. FZR Mode 900 Impact 2014 003 Accessories
  3. NICE750 Destroyer 2014 020

But then it fails on this string...

  1. We like the moon 2013 Stand 010

Is there another possible way to extract the 3 digit integer successfully with out getting confused with other integers. I guess it will have to be a clever bit of php to do this.

The only consistent pattern there is, is there is always a space infront of the 3 digits and either a full-stop or a space after the 3 digits.

  • 写回答

3条回答

  • dstnlhhv791576 2013-11-05 19:10
    关注

    the solidest way should be

    preg_match_all('!(\d{3})(?=(?:(?!\d{3}).)*$)!m', $str, $integer);
    

    see it in action here: http://regex101.com/r/pJ0xN4

    here's also a structural explanation:

    Regular expression visualization

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图