Search code examples
phppreg-matchfilenamespreg-grep

Preg-match filenames with hypens


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 />";
}

Solution

  • Use this regular expression

    /^2[-.]/
    

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