php for循环删除常用单词

I have a text file that maintains a list of words.

What I am trying to do is pass a string(sentence) to this function and remove the word from the string if it exists in the text file.

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

It doesn't seem to work however. The common words from the string are not being removed. instead I am getting the same string with the one I started.

I think I am doing the loop wrong. What is the correct approach and what am I doing wrong?

on the line

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

change it to

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

and remove the second for loop.

Try using str_replace():

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

Or in full:

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