繁体   English   中英

检查文件目录中的字符串,但不包括子目录

[英]Checking for string within a directory of files but not including subdirectories

我正在尝试编写一个程序,该程序将打开一个目录(在本例中为files /),扫描此目录中的所有文件名(不包括任何目录或“ ..”或“。”),并搜索“页面”数组中指定文件中的文件名。 如果在页面中找不到文件名,则文件将被移至“未使用的内容”。

我当前的代码不起作用。 我怎样才能实现这个目标?

<?php

if($handle = opendir('files/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $file_names[] = $entry;
        }
    }
    closedir($handle);
}

$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");

for($x=0; $x<sizeOf($pages); $x++) {
  $current_page = file_get_contents($pages[$x]);
    for($i=0; $i<sizeOf($file_names); $i++) {
        if(!strpos($current_page,$file_names[$i])) {
            if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
                unlink("files/".$file_names[$i]);
            }
        }
    }
}

?> 

谢谢!

您不需要所有那么长的代码..您所需要的只是FilesystemIterator

$pages = array("1.xml","page2.shtml","page_three.shtml","page4.htm","page5.shtml");
$dir = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
foreach ( $dir as $file ) {
    if ($file->isFile() && in_array(strlen($file->getFilename()), $pages)) {
        // copy
        // unlink
    }
}

查看使用GlobIterator的另一个示例

尝试做这样的事情:

<?php

if($handle = opendir('files/')) {
  $i=0;
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $file_names[$i] = $entry;
        }
        $i++;
    }
    closedir($handle);
}

$pages = array("page1.html","page2.shtml","page_three.shtml","page4.htm","page5.shtml");

for($x=0; $x<sizeOf($pages); $x++) {
  $current_page = file_get_contents($pages[$x]);
    for($i=0; $i<sizeOf($file_names); $i++) {
        if(!strpos($current_page,$file_names[$i])) {
            if (copy("files/".$file_names[$i],"files/unused-content/".$file_names[$i])) {
                unlink("files/".$file_names[$i]);
            }
        }
    }
}

?> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM