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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With