2011-12-20 78 views
0

我有一个文本文件保存单词列表。php for循环删除常见单词

我想要做的是传递一个字符串(句子)到这个函数,并从字符串中删除单词,如果它存在于文本文件中。

<?php 
error_reporting(0); 

$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning"; 

common_words($str1); 

function common_words($string) { 
$file = fopen("common.txt", "r") or exit("Unable to open file!"); 
$common = array(); 
while(!feof($file)) { 
    array_push($common,fgets($file)); 
    } 
fclose($file); 

$words = explode(" ",$string); 
print_r($words); 

for($i=0; $i <= count($words); $i+=1) { 
    for($j=0; $j <= count($common); $j+=1) { 
      if($words[$i] == $common[$j]){ 
      unset($words[$i]); 
      } 
     } 
    } 
} 
?> 

这似乎并不但是工作。字符串中的常见单词不会被删除。相反,我得到了与我开始的字符串相同的字符串。

我想我在做错误的循环。什么是正确的方法,我做错了什么?

+0

这是功课吗? – 2011-12-20 14:12:06

+0

不,这是我的项目的一个小部分... – SupaOden 2011-12-20 14:12:26

+0

尝试打印$ common数组,我认为您将整个文件内容插入到一个数组值中。 – YamahaSY 2011-12-20 14:15:45

回答

1

上线

 if($words[$i] == $common[$j]){ 

改变它

 if(in_array($words[$i],$common)){ 

并删除第二个for循环。

+0

嗯,这些之间的区别是什么二? – Neal 2011-12-20 14:15:33

+0

在我输入完成之前提交的文件 – macintosh264 2011-12-20 14:15:51

+0

那么这很愚蠢:-P – Neal 2011-12-20 14:16:23

1

尝试使用str_replace()

foreach($common as $cword){ 
    str_replace($cwrod, '', $string); //replace word with empty string 
} 

或全部:

<?php 
error_reporting(0); 

$str1= "the engine has two ways to run: batch or conversational. In batch, expert system has all the necessary data to process from the beginning"; 

common_words($str1); 

function common_words(&$string) { //changes the actual string passed with & 

    $file = fopen("common.txt", "r") or exit("Unable to open file!"); 

    $common = array(); 
    while(!feof($file)) { 
     array_push($common,fgets($file)); 
    } 
    fclose($file); 

    foreach($common as $cword){ 
     str_replace($cword, '', $string); //replace word with empty string 
    } 
} 
?> 
+0

也许只是代码风格使用file_get_contents()而不是fopen()太;) – 2011-12-20 14:15:07

+0

@ Hikaru-Shindo哈哈真的太,但我不想进入它:-P – Neal 2011-12-20 14:16:04

+0

这个工作也可以'$ arr = array_merge(array_diff($ words,$ common));'? – SupaOden 2011-12-20 14:25:09