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 优质github账号直接兑换rmb,感兴趣伙伴可以私信
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)