php for循环删除常用词

php for循环删除常用词,php,for-loop,Php,For Loop,我有一个文本文件,它维护一个单词列表 我试图做的是将一个字符串(句子)传递给这个函数,并从字符串中删除文本文件中存在的单词 <?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_wo

我有一个文本文件,它维护一个单词列表

我试图做的是将一个字符串(句子)传递给这个函数,并从字符串中删除文本文件中存在的单词

<?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]);
            }
        }
    } 
}
?>

然而,它似乎不起作用。未删除字符串中的常用词。相反,我得到的字符串与我开始的字符串相同

我认为我做的循环是错误的。正确的方法是什么?我做错了什么?

尝试使用:

或全部:

<?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
    }
}
?>

在线上

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

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

并删除第二个for循环。

不,这是我项目的一小部分…尝试打印$common数组,我认为您将整个文件内容插入到一个数组值中。为什么要使用
$I thing函数必须有返回语句:)@Liutas它不必,请参见我的答案。可能只是为了编码样式,请使用file\u get\u contents()而不是fopen()也是;)@Hikaru Shindo lol也是真的,但我不想参与其中:-PCan这项工作也
$arr=array\u merge(array\u diff($words,$common))?注意常用词中的“an”,以及(例如)句子字符串中的“sandcastle”。。。考虑使用PrggRead与\b字边界标记…请记住,您还可以将搜索数组传递给str_replace(和preg_replace)因此,不需要在循环中处理每个常用单词,它会给我相同的字符串…你的答案和那一个有什么区别?在我完成键入之前提交。这将消除第二个循环的需要。我3分钟前才发现这一点。修复不接受$common…但是
如果(在_数组($words[$i],数组(“the”,“an”)){
起作用。。。
        if(in_array($words[$i],$common)){