简体   繁体   English

PHP正则表达式:提取文件名中的最后一个数字

[英]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 假期(1).png 返回1

Vacation (Me and Mom) (2).png returns 2 假期(我和妈妈)(2).png 返回2

Vacation (5) (3).png returns 3 假期(5)(3).png 返回3

Hope some regex pros are out there :) 希望一些正则表达的专业人士在那里:)

This should do it ( demo on ideone.com ): 这应该做( 在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. 贪婪的^.*使正则表达式首先匹配尽可能多的字符,然后回溯直到它可以匹配\\((\\d+)\\) ,即括号括起来的数字。

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

\((\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

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 php test.php 1 2 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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