David
David

Reputation: 16726

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)

Upvotes: 2

Views: 175

Answers (2)

Loukan ElKadi
Loukan ElKadi

Reputation: 2867

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

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

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

Upvotes: 2

Related Questions