Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Case insensitive File Search

Tags:

php

glob

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.

like image 733
Gogol Avatar asked May 18 '15 12:05

Gogol


People also ask

Is File_exists case sensitive?

If not, the question is nonsense, as PHP's file_exists() is case-insensitive for files on case-insensitive file systems.

How to check whether file exists in PHP?

The file_exists() function checks whether a file or directory exists. Note: The result of this function is cached. Use clearstatcache() to clear the cache.

Is PHP case-insensitive?

In PHP, class names as well as function/method names are case-insensitive, but it is considered good practice to them functions as they appear in their declaration.

Is PHP case sensitive true or false?

In PHP, variable and constant names are case sensitive, while function names are not.


1 Answers

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.

like image 162
Gogol Avatar answered Oct 28 '22 13:10

Gogol