搜索重复php的数组



我使用PHP已经好几年了,我已经有点生疏了。我正在尝试编写一个快速脚本,打开一个大文件并将其拆分为一个数组,然后在每个值中查找类似的情况。例如,该文件由以下内容组成:

Chapter 1. The Beginning 
 Art. 1.1 The story of the apple
 Art. 1.2 The story of the banana
 Art. 1.3 The story of the pear
Chapter 2. The middle
 Art. 1.1 The apple gets eaten
 Art. 1.2 The banana gets split
 Art. 1.3 Looks like the end for the pear!
Chapter 3. The End
…

我希望脚本能自动告诉我,其中两个值中有字符串"apple",并返回"Art.1.1苹果的故事"one_answers"Art1.1苹果被吃掉了",然后对香蕉和梨也这样做。

我不想在数组中搜索特定的字符串,我只需要它来计算出现次数并返回内容和位置。

我已经有了打开一个文件,然后将其拆分为一个数组的脚本。只是不知道如何找到类似的事件。

<?php
$file = fopen("./index.txt", "r");
$blah = array();
while (!feof($file)) {
   $blah[] = fgets($file);
}
fclose($file);
var_dump($blah);
?>

如有任何帮助,我们将不胜感激。

这个解决方案并不完美,因为它统计了文本中的每一个单词,所以您可能需要对它进行修改,以更好地满足您的需求,但它提供了关于每个单词在文件中被提及的次数以及确切的行数的准确统计信息。

$blah = file('./index.txt') ;
$stats = array();
foreach ($blah as $key=>$row) {
    $words = array_map('trim', explode(' ', $row));
    foreach ($words as $word)
        if (empty($stats[$word]))  {
            $stats[$word]['rows'] = $key.", ";
            $stats[$word]['count'] = 1;
        } else {
            $stats[$word]['rows'] .= $key.", ";
            $stats[$word]['count']++;
        }
}
print_r($stats);

我希望这个想法能帮助你继续前进,并进一步完善,以更好地满足你的需求!

最新更新