Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex: extract last number in filename

Tags:

regex

php

I need a regex with extract me a number which is always at the end of a file wrapped in ().

For example:

Vacation (1).png returns 1

Vacation (Me and Mom) (2).png returns 2

Vacation (5) (3).png returns 3

Hope some regex pros are out there :)

like image 932
YeppThat'sMe Avatar asked Jan 15 '23 15:01

YeppThat'sMe


1 Answers

Just write it, $ is the end of the subject:

$pattern = '/\((\d+)\)\.png$/';
$number  = preg_match($pattern, $subject, $matches) ? $matches[1] : NULL;

This is a so called anchored pattern, it works very well because the regular expression engine knows where to start - here at the end.

The rest in this crazy pattern is just quoting all the characters that need quoting:

(, ) and . => \(, \) and \. in:

().png     => \(\)\.png

And then a group for matches is put in there to only contain one or more (+) digits \d:

\((\d+)\)\.png
  ^^^^^

Finally to have this working, add the $ to mark the end:

\((\d+)\)\.png$
              ^

Ready to run.

like image 178
hakre Avatar answered Jan 24 '23 19:01

hakre