-1

我希望此脚本从文本文件中读取每一行(都是 url)并对其进行解析以检查该特定网站的任何 url 中是否存在两个给定的单词。我还希望文本文件中的所有 url(行)都按序列号打印。此代码找出这两个词,但我不确定它们是否来自该站点的同一网址。它显示给定单词出现的次数而不是序列号。

<?php  
$mysearch = file("phpelist.txt");  

for($index = 0; $index <count($mysearch); $index++)  
{

    $mysearch[$index] = str_replace("\n", "", $mysearch[$index]);  
    $data = file_get_contents("$mysearch[$index]");  

    $searchTerm1 = 'about'; 

 if (stripos($data, $searchTerm1) !== false) {
     echo "$counter$.mysearch[$index]... FOUND WORD $searchTerm1<br>";
     $searchTerm2 = 'us';
     if (stripos($data, $searchTerm2) !== false) {
        echo "... FOUND WORD $searchTerm2<br>";
        } 
}    

    else
        { 
        echo "<br>";
        echo "$mysearch[$index]...not found<br>";
        }    
}
?>

脚本的输出如下:

'url1'...未找到

'url2'...未找到

'url3'...未找到

'url4'...未找到

'url5'...未找到 $.mysearch[5]... 找到有关... 找到我们 $.mysearch[6] 的字... 找到有关... 找到我们 $.mysearch[7] 的字... 找到关于... 找到我们的词

'url6'...未找到 $.mysearch[9]... 找到关于... 找到我们 $.mysearch[10]... 找到关于... 找到我们 $.mysearch[11] 的字... 找到有关 ... 找到我们 $.mysearch[12] 的字... 找到有关... 找到我们 $.mysearch[13] 的字... 找到有关... 找到我们的字

4

2 回答 2

0

我会做这样的事情:

$fp = file("phpelist.txt");
$urlList = file_get_contents($fp);
$urls = explode("\n", $urlList);

$counter = 0;
foreach ($urls as $url) {
  $counter++;
  if (preg_match_all('#\b(word1|word2)\b#',  $url, $matches)) {
      echo "line: $counter url : $url <br/>";
  }
}
于 2016-12-05T17:26:33.057 回答
0

您可以通过以下函数以简单的方式执行此操作:

<?php
    function findWordsInString($str, $arr) {
        $found = array();
        foreach ($arr as $cur) {
            if (stripos($str, $cur) !== false)
                $found[$cur] = stripos($str, $cur);
        }
        return $found;
    }
?>

然后,使用返回的值,您可以运行array_keys以获取找到的字符串值。它们的索引存储位置。

举个例子:

$str = "Hello, world. How are you?";
$arr = array("Hello", "world", "you", "Hi");

这将给出如下输出:

array(3) {
  ["Hello"]=>
  int(0)
  ["world"]=>
  int(7)
  ["you"]=>
  int(22)
}

在这种情况下,仅找到Helloworldyou,并且它们位于 、 和07位置22

于 2016-12-05T17:13:22.233 回答