【问题标题】:Regex to match numbers separated by dash (-) and get substring正则表达式匹配以破折号 (-) 分隔的数字并获取子字符串
【发布时间】:2013-05-01 20:51:00
【问题描述】:

我在一个目录中有很多图像文件,它们的 ID 在关于它所包含内容的一些描述之间。

这是该目录中文件的示例: 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

我想要的是获取图像的 ID *(nn-nn-nnnn) 并使用该子字符串重命名文件。

*n 作为数字。

上面列表的结果是:01-19-1084.JPG, 02-40-0453.JPG, 01-43-1597.JPG, 04-30-2436.JPG, 02- 26-0745.JPG, 01-43-1427.jpg.

这是我用来循环目录的代码:

 $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);
    }
 }

那么,我的 $pattern 将如何得到我想要的?

【问题讨论】:

    标签: php regex preg-match substring rename


    【解决方案1】:

    那不就是这样吗:

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

    解释:

    ^                      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
    

    现在() 中有 3 个组。您必须使用索引 1、2 和 3。

    【讨论】:

    • 不知道你为什么要用[0-9]而不是\d,但这肯定不是错误的
    • 一个错误:扩展名必须是\.jpg,而不是.jpg,因为.是一个元字符。
    • 正确,否则它将是通配符。谢谢
    • +1 您的 $pattern 是正确的,但我检查了其他答案以进行澄清。无论如何,谢谢!
    【解决方案2】:

    $pattern 必须是这样的:

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

    此模式可以检查文件名并获取 id 作为匹配组。还有 preg_math 返回数字,而不是字符串。匹配作为函数的第三个参数返回。而身体必须是这样的:

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

    $matches 是匹配字符串和组的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多