PHP для цикла, чтобы удалить общие слова - PullRequest
0 голосов
/ 20 декабря 2011

У меня есть текстовый файл, который содержит список слов.

Я пытаюсь передать строку (предложение) этой функции и удалить слово из строки, если оно существует в текстовом файле.

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

Это не такпохоже на работу однако.Общие слова из строки не удаляются.вместо этого я получаю ту же строку с той, которую я начал.

Я думаю, что я делаю цикл неправильно.Какой правильный подход и что я делаю не так?

Ответы [ 2 ]

1 голос
/ 20 декабря 2011

на линии

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

изменить на

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

и удалите второй цикл for.

1 голос
/ 20 декабря 2011

Попробуйте использовать 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
    }
}
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...