doushouj966020
2016-01-27 09:46 阅读 58
已采纳

如何使用Regex匹配字符串中的PHP time()或microtime()?

I currently have a regex command which matches php time in a string:

preg_match( '/([a-z]+)_([0-9]{9,})\.jpg/i', $aName, $lMatches );

How can I modify this to also match microtime() in the same match?

Examples:

foobar_1453887550.jpg (match)

foobar_1453887620.8717.jpg (match)

foobar_123.jpg (don't match)

foobar_adsf123123.jpg (don't match)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douxiandiyo58855 douxiandiyo58855 2016-01-27 09:52

    Add optional group using ?:

    preg_match( '/([a-z]+)_([0-9]{9,})(\.[0-9]{4,})?\.jpg/i', $aName, $lMatches );
    

    Here (\.[0-9]{4,})? is an optional group which can present or not in your string.

    Considering @trincot remark you can change optional group to (\.[0-9]+)? if ending zeroes will not present in milliseconds.

    preg_match( '/([a-z]+)_([0-9]{9,})(\.[0-9]+)?\.jpg/i', $aName, $lMatches ); 
    
    点赞 评论 复制链接分享
  • dongxun2089 dongxun2089 2016-01-27 10:09

    First of all, your regex above shouldn't match the second example: foobar_1453887620.8717.jpg

    Now if you want it to match a number of digits less than 9, after the '_' , you need to modify the {9,} as needed.

    {9,} matches the prior match (in this case a digit [0-9]), repeated nine times or above.

    • To include your second example(foobar_1453887620.8717.jpg) in the match, your regex should be:
      /([a-z]+)_([0-9.]{9,})\.jpg/i
    • To match your third example (foobar_123.jpg):
      /([a-z]+)_([0-9]{3,})\.jpg/i

    • To match your fourth example (foobar_adsf123123.jpg):
      /([a-z]+)_([0-9\w]{3,})\.jpg/i

    • To match all your examples above:
      /([a-z]+)_([0-9.\w]{3,})\.jpg/i

    点赞 评论 复制链接分享

相关推荐