Php Preg将文件名与hypens匹配

Php Preg将文件名与hypens匹配,php,preg-match,filenames,preg-grep,Php,Preg Match,Filenames,Preg Grep,如何在PHP中使用preg_match检查文件名 Filename=2.pdf 如果另一个文件名为2-2.pdf或2-3.pdf,它也应该匹配 这是催眠前的身份证。它不需要检查.pdf文件扩展名 $id = 2; $list = scandir("D:/uploads/"); $list = preg_grep("/^".$id."$/", $list); foreach ($list as $file) { echo $file . "<br />"; } $id=2;

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

Filename=2.pdf

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

这是催眠前的身份证。它不需要检查
.pdf
文件扩展名

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

foreach ($list as $file)
{
    echo $file . "<br />";
}
$id=2;
$list=scandir(“D:/uploads/”;
$list=preg_grep(“/^”。$id.“$/”,$list);
foreach($列表为$文件)
{
echo$文件。“
”; }
使用此正则表达式

/^2[-.]/
演示:

如何:

/^$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);
用法:

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