查找与子字符串匹配的目录中的所有文件和文件名
问题描述:
我正在循环查看目录中的文件列表,并且希望将我拥有的子字符串与文件名进行匹配。如果文件名包含子字符串,则返回该文件名,以便我可以删除它。我做了以下,它只是返回一切:查找与子字符串匹配的目录中的所有文件和文件名
while ($file = readdir($dir_handle)) {
$extension = strtolower(substr(strrchr($file, '.'), 1));
if($extension == "sql" || $extension == "txt") {
$pos = strpos($file, $session_data['user_id']);
if($pos === true) {
//unlink($file);
echo "$file<br />";
}else {
// string not found
}
}
}
我做错了什么?
感谢所有的帮助
答
strpos返回一个整数或FALSE。您将要更新的测试是
$pos !== FALSE
然后 - 如果你想删除您可以取消取消链接()调用的文件。我不确定你的意思是“归还,所以我可以删除”。
答
假设你是在Linux上,你可以使用[水珠()] [1]功能与GLOB_BRACE
选项做到这一点:
$files = glob('*.{sql,txt}', GLOB_BRACE);
您也可能会在混合USER_ID那里。
不确定它是否可以在Windows上使用。请参阅http://de.php.net/glob并介绍关于GLOB_BRACE
选项的说明。
答
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 />";
}
}
}
答
可以使用SPL做递归
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
}
}
太棒了!我没有尝试这种组合! :P – Abs 2010-01-07 00:58:28