2013-10-01 81 views
1
$domains = file('../../domains.txt'); 
$keywords = file('../../keywords.txt'); 

$域将在格式:我将如何比较两个文本文件匹配与PHP

3kool4u.com,9/29/2013 12:00:00 AM,AUC 
3liftdr.com,9/29/2013 12:00:00 AM,AUC 
3lionmedia.com,9/29/2013 12:00:00 AM,AUC 
3mdprod.com,9/29/2013 12:00:00 AM,AUC 
3mdproductions.com,9/29/2013 12:00:00 AM,AUC 

关键字将在格式:

keyword1 
keyword2 
keyword3 

我想我会真的很想为文件中的关键字做一个数组,并搜索每一行domains.txt中的匹配项。不知道从哪里开始,因为我对preg_match,preg_match_all和strpos的差异感到困惑,并且多少会在何时使用另一个。

非常感谢您的帮助。

+0

关键字和域名之间的关系是什么? – anupam

+0

没有关系,只是搜索包含字符串作为domains.txt文件每天更改。 – CodingNoob

回答

2
//EMPTY array to hold each line on domains that has a match 
$matches = array(); 

//for each line on the domains file 
foreach($domains as $domain){ 

    //for each keyword 
    foreach($keywords as $keyword){ 

      //if the domain line contains the keyword on any position no matter the case 
      if(preg_match("/$keyword/i", $domain)) { 
        //Add the domain line to the matches array 
      $matches[] = $domain; 
      }  
    } 
} 

现在你有$匹配阵列相匹配的关键字的

注意到,与以前的方法的两个的整个文件加载到内存中,并且根据所访问的文件中的所有行文件大小可以运行内存不足或OS将开始使用比RAM

慢得多,这是另一个和更有效的方法,可以加载一行交换,如果该文件的时间。

<?php 

// Allow automatic detection of line endings 
ini_set('auto_detect_line_endings',true); 

//Array that will hold the lines that match 
$matches = array(); 

//Opening the two files on read mode 
$domains_handle = fopen('../../domains.txt', "r"); 
$keywords_handle = fopen('../../keywords.txt', "r"); 

    //Iterate the domains one line at the time 
    while (($domains_line = fgets($domains_handle)) !== false) { 

     //For each line on the domains file, iterate the kwywords file a line at the time 
     while (($keywords_line = fgets($keywords_handle)) !== false) { 

       //remove any whitespace or new line from the beginning or the end of string 
       $trimmed_keyword = trim($keywords_line); 

       //Check if the domain line contains the keyword on any position 
       // using case insensitive comparison 
       if(preg_match("/$trimmed_keyword/i", trim($domains_line))) { 
        //Add the domain line to the matches array 
       $matches[] = $domains_line; 
       } 
     } 
     //Set the pointer to the beginning of the keywords file 
     rewind($keywords_handle); 
    } 

//Release the resources 
fclose($domains_handle); 
fclose($keywords_handle); 

var_dump($matches); 
+0

这似乎工作,但是当我在我的服务器上运行top时,我的VPS的CPU使用率为99%。有没有办法清除每一行的内存? – CodingNoob

+1

是的。问题是,当你使用函数file()时,整个文件被加载到内存中并占用大量内存。我的建议是不要使用。 file()函数。改用fopen()和fread()。这个函数不会加载整个文件。我会在到达我的工作时发表一个例子。 – slash28cu

+1

@IsaacBoda我编辑了答案并编写了一个更加高效的脚本,它不会加载整个文件。逐行阅读。 – slash28cu