Skip to content

Instantly share code, notes, and snippets.

@relliv
Last active January 5, 2022 17:07
Show Gist options
  • Save relliv/9ce164b82ad936a3832f5ff9cdc6ae4d to your computer and use it in GitHub Desktop.
Save relliv/9ce164b82ad936a3832f5ff9cdc6ae4d to your computer and use it in GitHub Desktop.
Search file or files in folder with PHP

"/([0-9]+)-([0-9]+)(.*)\.wav/" the regex pattern depends to your case and $matches[1] == $needle part in if block should be change to instead given pattern.

<?php
private function scanDir($target, $needle){
if (file_exists($target)){
$it = new RecursiveDirectoryIterator($target, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
$numberMatches = [];
foreach($files as $file) {
preg_match("/([0-9]+)-([0-9]+)(.*)\.wav/", $file, $matches);
if ($matches && $matches[1] == $needle && file_exists($file)) {
$numberMatches[] = $file;
}
}
if (count($numberMatches)) {
return $numberMatches;
}
}
return null;
}
<?php
private function scanDir($target, $needle){
if (file_exists($target)){
$it = new RecursiveDirectoryIterator($target, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
preg_match("/([0-9]+)-([0-9]+)(.*)\.wav/", $file, $matches);
if ($matches && $matches[1] == $needle && file_exists($file)) {
return $file;
}
}
}
return null;
}
<?php
private function scanDir($target, $needle){
if (file_exists($target)){
$files = array_diff(scandir($dir), array('.', '..'));
foreach($files as $file) {
preg_match("/([0-9]+)-([0-9]+)(.*)\.wav/", $file, $matches);
if ($matches && $matches[1] == $needle && file_exists($file)) {
return $file;
}
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment