robertwbradford
robertwbradford

Reputation: 6585

In PHP, find an existing file using a regex pattern for the file name

I'm aware of the glob function. However, I am needing to match a regex pattern. Say I have the following directory of files:

/assets
  |- logo-abd6d458.png
  |- logo-big-bd7543cd.png
  |- another-ab87dbf0.css
  +- something-784b52ac.png

I need a PHP function that should return a filename of an existing file in this directory when I only know the start of the file name and the extension. For example:

function asset_name($start, $extension) {
  // Some magic here
}

asset_name('logo', 'png'); should return "logo-abd6d458.png", but it should not return "logo-big-bd7543cd.png".

asset_name('logo-big', 'png'); should return "logo-big-bd7543cd.png".

Can anyone figure out the "magic" for this function? I can't seem to wrap my head around it. Thanks.

UPDATE: The assets directory is a copy of another directory, however each of the files are renamed to include a hyphen and then an eight-character unique hash at the end of the file name (for cache-busting). So an original file logo.png will be renamed to logo-abd6d458.png. Another file such as logo-big.something.else.here.png would become logo-big.something.else.here-dcba4321.png and I would then use asset_name('logo-big.something.else.here', 'png');.

When calling the function I would always be using the whole original filename for $start and the extension for $extension.

Upvotes: 4

Views: 4697

Answers (1)

Alfwed
Alfwed

Reputation: 3282

Here's one way to do it based on your exemples.

I'm assuming that your checksum is of fixed length so you can just remove the (10+length of extension)th last chars of the filename and make the comparison.

<?php

function asset_name($start, $ext)
{
    $dir = 'assets';
    $files = glob($dir.'/*.'.$ext);

    $suffixLength = -9 - strlen($ext) - 1;
    foreach ($files as $file) {
        $name = substr($file, strlen($dir)+1, $suffixLength);
        if ($name === $start) {
            return $file;
        }
    }

    throw new Exception('file not found');
}

$file = asset_name('logo', 'png');

Upvotes: 2

Related Questions