1

How do I check filenames with preg_match in PHP?

Filename = 2.pdf

It should also match if another file is called 2-2.pdf or 2-3.pdf.

It's the Id before the hypen. It dont need to check the .pdf file extension.

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

foreach ($list as $file)
{
    echo $file . "<br />";
}
Toto
  • 89,455
  • 62
  • 89
  • 125
Stefan Frederiksen
  • 135
  • 2
  • 3
  • 15

2 Answers2

1

How about:

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

Explanation:

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

Usage:

$list = preg_grep("/^$id(?:-\d+)?/", $list);
Toto
  • 89,455
  • 62
  • 89
  • 125
0

Use this regular expression

/^2[-.]/

Demo: http://regex101.com/r/aJ7cK0/1

Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29