[英]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['user_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. strpos返回一个整数或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. 然后-如果要删除文件,则可以取消注释unlink()调用。 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: 假设您使用的是Linux,则可以使用带有
GLOB_BRACE
选项的[glob()] [1]函数进行此GLOB_BRACE
:
$files = glob('*.{sql,txt}', GLOB_BRACE);
You might also mix in the user_id there. 您也可以在其中混入user_id。
Not sure if it works on Windows. 不知道它是否可以在Windows上运行。 See http://de.php.net/glob and mind the note about the
GLOB_BRACE
option. 请参阅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 />";
}
}
}
you can use SPL to do it recursively 您可以使用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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.