【问题标题】:Preg-match filenames with hypens预匹配文件名与连字符
【发布时间】:2014-10-11 12:59:06
【问题描述】:

如何在 PHP 中使用 preg_match 检查文件名?

文件名 = 2.pdf

如果另一个文件被称为2-2.pdf2-3.pdf,它也应该匹配。

这是hypen之前的Id。它不需要检查.pdf文件扩展名。

$id = 2;
$list = scandir("D:/uploads/");
$list = preg_grep("/^".$id."$/", $list);

foreach ($list as $file)
{
    echo $file . "<br />";
}

【问题讨论】:

    标签: php preg-match filenames preg-grep


    【解决方案1】:

    怎么样:

    /^$id(?:-\d+)?/
    

    说明:

    /        : delimiter
    ^        : begining of strig
    $id      : the id defined earlier
    (?:      : begining of non capture group
        _    : a dash
        \d+  : one or more digits
    )?       : end of group, optional
    /        : delimiter
    

    用法:

    $list = preg_grep("/^$id(?:-\d+)?/", $list);
    

    【讨论】:

      【解决方案2】:

      使用这个正则表达式

      /^2[-.]/
      

      演示:http://regex101.com/r/aJ7cK0/1

      【讨论】:

        猜你喜欢
        • 2011-03-19
        • 2016-05-27
        • 2019-01-27
        • 1970-01-01
        • 2015-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多