Gogol
Gogol

Reputation: 3070

PHP - Case insensitive File Search

I need to check the image folder for adding some product images. My product list array has SKUs such as a48be25, A48be29, A48BE30 and my image folder has images such as a48BE25_1.jpg, a48bE29_2.JPG, A48BE30_1.jpg and so on.

As you can see, the images and SKUs are mixed. I need to somehow match SKUs to the file names. If I use glob("my/dir/{$SKU}*.jpg"), it won't work in case sensitive operating systems according to the best of my knowledge. Is there a way to force glob to search in a case-insensitive way?

EDIT: I don't think this thread is a duplicate of this one. I am saying this because in my case I can have many SKUs that can have mixed cases. In the mentioned thread, OP only had the word CSV in mixed cases, so glob('my/dir/*.[cC][sS][vV]') could work well there.

Upvotes: 7

Views: 2688

Answers (1)

Gogol
Gogol

Reputation: 3070

I ultimately ended up fetching all images from the folder and checking for each sku in the image name array.

The following code solved my problem:

$path = $image_path ."/*.{jpg,png,gif}";
$all_images = glob($path, GLOB_BRACE);
$icount = count($all_images);
for($i = 0; $i < $icount; $i++)
{
    $all_images[$i] = str_replace($image_path.'/', '', $all_images[$i]);
}

foreach($products as $product){
    $matches  = preg_grep ('/^'.$product['sku'].'(\w+)/i', $all_images);
}

Nevertheless, I would love to see case-insensitive glob implemented in future.

Upvotes: 3

Related Questions