搜索具有特定名称的 txt 文件,然后使用 PHP 将其删除


Search for txt files with a certain name and then delete them using PHP?

使用 php 中的取消链接功能,可以在包含多个文件夹的目录中搜索具有特定名称的 txt 文件。就我而言Newsfeed.txt

我应该从哪里开始?

很好的答案maxhb。这里有一些更手动的东西。

<?php
function unlink_newsfeed($checkThisPath) {
    $undesiredFileName = 'Newsfeed.txt';
    foreach(scandir($checkThisPath) as $path) {
        if (preg_match('/^('.|'.'.)$/', $path)) {
            continue;
        }
        if (is_dir("$checkThisPath/$path")) {
            unlink_newsfeed("$checkThisPath/$path");
        } else if (preg_match( "/$undesiredFileName$/", $path)) {
            unlink("$checkThisPath/$path");
        }
    }
}
unlink_newsfeed(__DIR__);

您可以使用 php 标准库 (SPL) 的递归目录迭代器。

function deleteFileRecursive($path, $filename) {
  $dirIterator = new RecursiveDirectoryIterator($path);
  $iterator = new RecursiveIteratorIterator(
    $dirIterator,
    RecursiveIteratorIterator::SELF_FIRST
  );
  foreach ($iterator as $file) {
    if(basename($file) == $filename) unlink($file);
  }
}
deleteFileRecursive('/path/to/delete/from/', 'Newsfeed.txt');

这将允许您从给定文件夹和所有子文件夹中删除名称为Newsfeed.txt的所有文件。