【问题标题】:PHP how to get all files(only html files) in all subdirectories and index each html pagePHP如何获取所有子目录中的所有文件(仅html文件)并索引每个html页面
【发布时间】:2011-09-23 05:55:13
【问题描述】:

对于家庭作业,我必须获取当前目录和所有子目录中的所有 .htm 和 .html 文件,并且必须通过单独计算文件中出现的所有单词来对它们进行索引。

在目录中找到 html 文件后,我将如何计算文件:

$file = '.html';
$index = indexer($file);
echo '<pre>'.print_r($index,true).'</pre>';

function indexer($file) {
    $index = array();
    $find = array('/\r/','/\n/','/\t/','!',',','.','"',';',                           ':');
    $replace = array(' ',' ',' ',' ',' ',' ',' ',' ',' ');
    $string = file_get_contents($file);
    $string = strip_tags($string);
    $string = strtolower($string);
    $string = str_replace($find, $replace, $string);
    $string = trim($string);
    $string = explode(' ', $string);
    natcasesort($string);
    $i = 0;
    foreach($string as $word) {
        $word = trim($word);
        $ignore = preg_match('/[^a-zA-Z]/', $word);
        if($ignore == 1) {
            $word = '';
        }
        if( (!empty($word)) && ($word != '') ) {
            if(!isset($index[$i]['word'])) {
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            } elseif( $index[$i]['word'] == $word ) {
                $index[$i]['count'] += 1;
            } else {
                $i++;
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            }
        }
    }
    unset($work);
    return($index);
}

我只需要首先弄清楚如何找到目录中的所有 htm 或 html 文件,然后开始在每个 htm/html 文件上使用上述代码。任何帮助将不胜感激,谢谢!

【问题讨论】:

标签: php html directory indexing


【解决方案1】:

好吧,因为这是家庭作业,所以我不会给你代码。但我可以为你指出正确的方向。通常对于这种类型的事情,人们使用递归函数。函数调用自身的地方。

此函数应执行以下操作:

  • 统计当前目录下所有htm和html文件的所有行数。
  • 将这些数字相加,然后将它们添加到函数外部的全局变量中(只需使用 global,您可以返回每次调用的行数,然后将它们相加,但这很麻烦)李>
  • 为当前目录中的每个文件夹再次调用此函数(循环遍历它们)
  • 回到起点后,重置全局变量并返回其值

【讨论】:

  • 我似乎不知道如何实现递归函数并将上面的代码实现到数组中存储的每个htm/html文件。总的来说,我对 PHP 和编码还很陌生。
【解决方案2】:

尝试使用glob 函数。

$files = glob('*.htm*');
foreach($files as $file) {
//code here
}

已编辑:

    function readDir($path) {
  $files = glob($path . '*.*');

  foreach ($files as $file) {
    if (is_dir($file)) {
      $html_files = array_merge((array) readDir($file . '/'), (array) $html_files);
    }

    if (in_array(strtolower(end(explode('.', $file))), array('html', 'htm'))) {
      $html_files[] = $file;
    }
  }

  return $html_files;
}

刚刚编辑了答案,试试这个。 (注意:我没有在任何网站上测试过代码。) 谢谢

【讨论】:

  • 这不会递归工作。该问题要求当前目录和所有子目录。
  • 我必须先在当前目录和子目录中搜索所有 .htm 文件,然后插入上面的代码。我必须使用什么代码/功能来做到这一点?
【解决方案3】:

这是使用RecursiveIteratorIteratorRecursiveDirectoryIteratorpathinfo() 的替代方法。

<?php

$dir = '/';

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::CHILD_FIRST);

foreach ( $iterator as $path )
  if ( $path->isFile() && preg_match('/^html?$/i', pathinfo($path->getFilename(), PATHINFO_EXTENSION)) )
    echo $path->getPathname() . PHP_EOL;

如果需要获取当前工作目录,可以使用getcwd()(即$dir = getcwd();)。

要获得内容的长度,您可以做一些事情。您可以使用file_get_contents 检索文件的内容,并使用strlen 计算长度或使用str_word_count 计算字数。另一种选择是使用$path-&gt;getSize()

如果您使用数组来存储名称和大小,则可以使用自定义函数和uasort 按大小对数组进行排序。

一个更完整的例子:

<?php

function sort_by_size($a, $b)
{
  if ( $a['size'] == $b['size'] )
    return 0;

  return ( $a['size'] < $b['size'] ? -1 : 1 );
}

$dir = '/';
$files = array();

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::CHILD_FIRST);

foreach ( $iterator as $path )
  if ( $path->isFile() && preg_match('/^html?$/i', pathinfo($path->getFilename(), PATHINFO_EXTENSION)) )
    $files[] = array(
      'name' => $path->getPathname(),
      'size' => $path->getSize()
    );

uasort($files, sort_by_size);

然后可以使用foreach 循环循环$files 数组。它将包含路径名和大小。

【讨论】:

  • (tip) 还有GlobIteratorRegexIteratorFilterIterator也有
【解决方案4】:

您对可以使用的函数/类有任何限制吗?如果没有,请查看RecursiveDirectoryIterator,它将让您通过 dirs 递归迭代目录中的所有项目。然后,您可以匹配每个项目的扩展名,如果匹配,则基本上进行计数。

另一种方法是在遍历目录时使用glob,这样您就可以像使用*nix 实用程序find 一样进行*.html 搜索。

至于计数,您可能想看看str_word_count

【讨论】:

  • 计数部分是我负责的,但我不确定如何循环上面的代码,甚至不知道如何在当前和子目录中找到所有 htm/html 文件并将它们存储在一个数组。
【解决方案5】:

RecursiveDirectoryIterator 是 PHP 中执行此操作的最佳类。它既灵活又快速。

Directory to array with PHP”中描述了其他替代方法(非递归)。在我对这个问题的回答中,我对其他答案给出的不同方法进行了计时,但是 PHP 代码中的所有解决方案都比使用 PHP 的 SPL 类慢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 2018-07-02
    相关资源
    最近更新 更多