根据其中出现的单词对数组中的文件进行排序,php

Sorting files in an array by the ocurrences of a word in it, php

我正在制作一个搜索栏,用于搜索目录中搜索到该词的文件,然后我希望将其添加到一个数组中,顺序是这个词被问的次数多,问的次数少. 我正在研究 PHP 这是我的代码:

<?php
    
    if(isset($_POST['busqueda'])){
        $variable = utf8_encode($_POST['busqueda']);
    }
    $Array1 = array();

    foreach(glob("*.txt") as $filename) {
        $contents = file_get_contents($filename);
        if (strpos($contents, $variable)){
             $Array1[] = $filename;
      }
    }

我不知道具体怎么做,我想我应该使用 substr_count(file_get_contents($Array1[$position1])) 或类似的东西,但我不确定如何制作排序系统,有人可以帮助我吗!

print_r($Array1);

for($var1=0; $var1<sizeof($Array1); $var1++){
       echo "times on the file: ".$Array1[$var1]."<br>";
        echo substr_count(file_get_contents($Array1[$var1]));
  }
?>

您可以使用 substr_count 本身。然后需要用arsort对数组进行排序。

$Array1 = array();
foreach (glob("*.txt") as $filename) {
    $contents = file_get_contents($filename);
    if ( ($count = substr_count($contents, $variable)) ) {
        $Array1[$filename] = $count;
    }
}

arsort($Array1) ;

print_r($Array1);

foreach ($Array1 as $file => $count) {
    echo "times on the file($file): $count <br>";
}

Bash(至少在 Linux 和 Mac 操作系统上可用)使完成任务变得极其容易,因为您可以通过 PHP 调用命令' s exec 函数,假设它没有被管理员禁用。如果您使用 Windows,那么这可能行不通,但大多数人在生产环境中使用 Linux,所以我认为这个答案值得发布。

以下函数取自 CodeIgniter 的文件助手,仅用于从指定目录中获取文件名数组。如果您因为从其他地方获取文件名而不需要这样的函数,请注意此函数可以包含每个文件的完整文件路径,这就是我使用它的原因。

function get_filenames($source_dir, $include_path = FALSE, $_recursion = FALSE)
{
    static $_filedata = array();

    if ($fp = @opendir($source_dir))
    {
        // reset the array and make sure $source_dir has a trailing slash on the initial call
        if ($_recursion === FALSE)
        {
            $_filedata = array();
            $source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
        }

        while (FALSE !== ($file = readdir($fp)))
        {
            if (@is_dir($source_dir.$file) && strncmp($file, '.', 1) !== 0)
            {
                get_filenames($source_dir.$file.DIRECTORY_SEPARATOR, $include_path, TRUE);
            }
            elseif (strncmp($file, '.', 1) !== 0)
            {
                $_filedata[] = ($include_path == TRUE) ? $source_dir.$file : $file;
            }
        }
        return $_filedata;
    }
    else
    {
        return FALSE;
    }
}

既然我可以轻松获取文件名数组,我会这样做:

/**
 * Here you can see that I am searching 
 * all of the files in the script-library 
 * directory for the word "the"
 */
$searchWord = 'the';
$directory = '/var/www/htdocs/script-library';

$filenames = get_filenames(
    $directory,
    TRUE    
);

foreach( $filenames as $file )
{
    $counts[$file] = exec("tr ' ' '\n' < " . $file . " | grep " . $searchWord . " | wc -l");
}

arsort( $counts );

echo '<pre>';
print_r( $counts );
echo '</pre>';

有关其工作原理的详细解释,请参阅:https://unix.stackexchange.com/questions/2244/how-do-i-count-the-number-of-occurrences-of-a-word-in-a-text-file-with-the-comma

我在本地测试了这段代码,效果很好。