YeppThat'sMe
YeppThat'sMe

Reputation: 1862

PHP Regex: extract last number in filename

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

Upvotes: 4

Views: 912

Answers (4)

RStrad
RStrad

Reputation: 162

<?php
    $pattern = '/(.+)\((\d+)\)\.png/';
    $test1 = "Vacation LDJFDF(1).png";
    $test2 = "Vacation (Me and Mom) (2).png";
    $test3 = "Vacation (5)(3).png";

    preg_match($pattern, $test1, $matches);
    print $matches[2];
    print "\n";

    preg_match($pattern, $test2, $matches);
    print $matches[2];
    print "\n";

    preg_match($pattern, $test3, $matches);
    print $matches[2];
    print "\n";

?>

php test.php 1 2 3

Upvotes: 0

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

Keep it simple. Use preg_match_all

preg_match_all('/\((\d+)\)/', $filename, $m); 
$num=end(end($m));

Upvotes: 1

Ilmari Karonen
Ilmari Karonen

Reputation: 50328

This should do it (demo on ideone.com):

preg_match( '/^.*\((\d+)\)/s', $filename, $matches );
$number = $matches[1];

The greedy ^.* causes the regexp to first match as many characters as possible, and then to backtrack until it can match \((\d+)\), i.e. a number surrounded by parentheses.

Upvotes: 4

hakre
hakre

Reputation: 197757

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.

Upvotes: 4

Related Questions