Search code examples
phpregexstringpreg-match

How can I match a filename containing an ID in a specific way?


I have image filenames and I'm trying to find them by some id($id) that is contained in their names.

The filenames always have the same structure:

something-$id(optional: numbers)(optional: -something).jpg

Now I want to match all filenames, which contain the id and are in the format like above described.

I tried the following to find the id with strpos():

$s = substr($file, strpos($file, $id), strlen($id));

But this also finds the id even if it has numbers in front of it, e.g. $id = 230 and filenames contain 2230. But as described in the format above there can't be any numbers before the id.

So can I do this without a regex to find filenames, which contain the id in that specific format or should I use a regex and if yes how?


Solution

  • A regex is more flexible here, so something like this would work for you:

    $pattern = "/^.*-$id(\d*)?(-.*)?\.jpg$/";
    

    You then can simply use this together with preg_match(), e.g.

    if(preg_match($pattern, $input)){
        //It matches
    }