Posts Tagged ‘search’
Search files using PHP with a mask pattern
This morning, I cam to a very, very basic need: detect whether a file matching a specific pattern (like ‘*.txt’) is available.
However, I could not find any ready to use PHP function, although PHP5 provides some interesting functions, like scandir().
After completing writting such a function, I decided to share it. So here is it.
Bare in mind it requires PHP5 (or later), as it relies on scandir() and on fnmatch(). Finally, this function while return the filtered directory content, regardless of the content being a file, a link or a directory.
Additional feature: by default, if you call the function more than once in your script in order to scan the same directory, it will read the directory only once: next times, it will use a cached content. To disable caching, set the third parameter to 1.
function searchdir( $path='.', $mask='*', $nocache=0 ){ static $dir = array(); if ( !isset($dir[$path]) || $nocache) { $dir[$path] = scandir($path); } foreach ($dir[$path] as $i=>$entry) { if ($entry!='.' && $entry!='..' && fnmatch($mask, $entry) ) { $sdir[] = $entry; } } if ($nocache) unset($dir); return ($sdir); }
Did you find this small function useful? Do you have any improvment suggestion?