繁体   English   中英

PHP如何获取所有子目录中的所有文件(仅html文件)并为每个html页面建立索引

[英]PHP how to get all files(only html files) in all subdirectories and index each html page

对于家庭作业,我必须获取当前目录和所有子目录中的所有.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文件上开始使用以上代码。 任何帮助将不胜感激,谢谢!

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

此功能应执行以下操作:

  • 计算当前目录中所有htm和html文件的所有行。
  • 将这些数字加起来,然后将它们添加到函数外部的全局变量中(只需使用global,您可以返回每个调用的行数,然后将它们相加,但这很麻烦)
  • 对当前目录中的每个文件夹再次调用此函数(只需遍历它们)
  • 一旦回到最开始,请重置全局变量,然后返回其值

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

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

尝试使用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;
}

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

这是使用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->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循环foreach $files数组。 它将包含路径名和大小。

您对可以使用的功能/类有任何限制吗? 如果不是,请签出RecursiveDirectoryIterator它将使您递归遍历目录中的所有项目。 然后,您可以匹配每个项目的扩展名,如果基本匹配,则可以进行计数。

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

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

暂无
暂无

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

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