phpregextimemicrotime

How to use Regex to match PHP time() or microtime() in a string?


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)


Solution

  • 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 );