简体   繁体   中英

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

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+)\\) , ie a number surrounded by parentheses.

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.

Keep it simple. Use preg_match_all

preg_match_all('/\((\d+)\)/', $filename, $m); 
$num=end(end($m));
<?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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM