Search code examples
phpregexdrupal-7

Regular expression filename matching


I am writing a PHP function in Drupal to detect duplicate file uploads and attempting to compare the uploaded filename to previously uploaded files.

I have example files of:

trees-nature_0.jpg
trees-nature_1.jpg
trees-nature0.jpg
trees-nature.jpg

I am trying to match all of them all using the following code:

file_scan_directory('image/uploads', "/trees-nature[*]?.jpg/");

However, all I get back is trees-nature.jpg.

I would appreciate some correction.


Solution

  • You can use the following:

    file_scan_directory('image/uploads', '/trees-nature(.*?)\.jpg/');
    

    Correction:

    • [ ] cannot be used as parentheses.. it has special meaning in regex
    • * is not wildcard in regex.. you have to use .*
    • . also has special meaning here (any character) you need to escape it