简体   繁体   English

正则表达式以匹配用短划线(-)分隔的数字并获取子字符串

[英]Regex to match numbers separated by dash (-) and get substring

I have a lot of image files in a directory with their ID between some descriptions about what it contains. 我的目录中有很多图像文件,它们的ID位于有关其内容的一些描述之间。

This is an example of the files in that directory: de-te-mo-01-19-1084 moldura.JPG, ce-ld-ns-02-40-0453 senal.JPG, dp-bs-gu-01-43-1597-guante.JPG, am-ca-tw-04-30-2436 Tweter.JPG, am-ma-ac-02-26-0745 aceite.JPG, ca-cc-01-43-1427-F.jpg 这是该目录中文件的示例: de-te-mo-01-19-1084moldura.JPG,ce-ld-ns-02-40-0453 senal.JPG,dp-bs-gu-01-43 -1597-guante.JPG,am-ca-tw-04-30-2436 Tweter.JPG,am-ma-ac-02-26-0745 aceite.JPG,ca-cc-01-43-1427-F.jpg

What I want is to get the ID of the image * (nn-nn-nnnn) and rename the file with that sub-string. 我想要的是获取图像的ID * (nn-nn-nnnn),然后使用该子字符串重命名文件。

*n as a number. * n为数字。

The result from the list above would be like: 01-19-1084.JPG, 02-40-0453.JPG, 01-43-1597.JPG, 04-30-2436.JPG, 02-26-0745.JPG, 01-43-1427.jpg . 上面列表中的结果将是: 01-19-1084.JPG,02-40-0453.JPG,01-43-1597.JPG,04-30-2436.JPG,02-26-0745.JPG, 01-43-1427.jpg

This is the code I'm using to loop the directory: 这是我用来循环目录的代码:

 $dir = "images";

 // Open a known directory, and proceed to read its contents
 if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if($sub_str = preg_match($patern, $file))
            {
                rename($dir.'/'.$file, $sub_str.'JPG');
            }
        }
        closedir($dh);
    }
 }

So, how my $patern would be to get what I want? 那么,我的$ patern如何获得我想要的?

Wouldn't that be just like: 那会不会像:

^.*([0-9]{2})-([0-9]{2})-([0-9]{4}).*\.jpg$

Explain: 说明:

^                      Start of string
.*                     Match any characters by any number 0+
([0-9]{2})             2 Digits
-                      Just a - char
([0-9]{2})             2 Digits
-                      Just a - char
([0-9]{4})             4 Digits
-                      Just a - char
.*                     Any character
\.jpg                  Extension and escape wildcard
$                      End of string

Now you got 3 groups inside the () . 现在()有3个组。 You have to use index 1, 2 and 3. 您必须使用索引1、2和3。

$pattern must be like this: $ pattern必须是这样的:

$pattern = "/^.*(\d{2}-\d{2}-\d{4}).*\.jpg$/i"

This pattern can check file name and get id as match group. 此模式可以检查文件名并获取ID作为匹配组。 Also preg_math return number, not string. 还有preg_math返回数字,而不是字符串。 Matches return as third param of function. 匹配返回作为函数的第三个参数。 while body must looks like this: 而身体必须看起来像这样:

if(preg_match($patern, $file, $matches))
{
      rename($dir.'/'.$file, $matches[1].'.JPG');
}

$matches is array with matched string and groups. $ matches是具有匹配的字符串和组的数组。

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

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