【问题标题】:Search for txt files with a certain name and then delete them using PHP?搜索具有特定名称的txt文件,然后使用PHP删除它们?
【发布时间】:2016-05-11 18:23:26
【问题描述】:

使用 php 中的 unlink 功能可以在具有多个文件夹的目录中搜索具有特定名称的 txt 文件。在我的情况下Newsfeed.txt

我应该从哪里开始?

【问题讨论】:

标签: php html recursion directory unlink


【解决方案1】:

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

【讨论】:

  • 好吧,我应该解释一下 php 对我来说很新。所以第一部分搜索一个集合目录并将所有结果放入$dirItnerator。我明白了。
  • 但我不明白如何在 $dirIterator 中搜索名为 Newsfeed.txt 的文件?并取消所有链接?对不起
  • 编辑示例以满足您的要求。
【解决方案2】:

很好的答案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__);

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多