Find all files and filenames in a directory that match a substring
I am looping through a list of files in a directory and I want to match a substring that I have with the filename. If the filename contains the substring then return that file name so that I can delete it. I have done the following and its just returning everything:
while ($file = readdir($dir_handle)) {
$extension = strtolower(substr(strrchr($file, '.'), 1));
if($extension == "sql" || $extension == "txt" ) {
$pos = strpos($file, $session_data['us开发者_如何转开发er_id']);
if($pos === true) {
//unlink($file);
echo "$file<br />";
}else {
// string not found
}
}
}
What am I doing wrong?
Thanks all for any help
strpos returns an integer or FALSE. You'll want to update your test to be
$pos !== FALSE
Then - if you want to delete the file you can uncomment the unlink() call. I'm not sure what you mean by "return so I can delete".
Assuming you are on Linux you can do this using the [glob()][1] function with the GLOB_BRACE
option:
$files = glob('*.{sql,txt}', GLOB_BRACE);
You might also mix in the user_id there.
Not sure if it works on Windows. See http://de.php.net/glob and mind the note about the GLOB_BRACE
option.
if ($handle = opendir('/path/to/dir/') {
$extensions = array('sql' => 1, 'txt' => 1);
while (false !== ($file = readdir($handle))) {
$ext = strtolower(substr(strrchr($file, '.'), 1));
if (isset($extensions[$ext]) && strpos($file, $session_data['user_id']) !== false)
echo "$file<br />";
else
echo "no match<br />";
}
}
}
you can use SPL to do it recursively
foreach (new DirectoryIterator('/path') as $file) {
if($file->isDot()) continue;
$filename = $file->getFilename();
$pathname = $file->getPathname();
if ( strpos ($filename ,".sql") !==FALSE ) {
echo "Found $pathname\n";
$pos = strpos($filename, $session_data['user_id']);
......
#unlink($pathname); #remove your file
}
}
精彩评论