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

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

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

我应该从哪里开始呢?

您可以使用 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 的所有文件。

伟大的答案 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__);