我有一个文本文件,用于维护单词列表。
我要做的是将一个字符串(句子)传递给此函数,如果该字符存在于文本文件中,则从字符串中删除该字。
<?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 :(得分: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
}
}
?>
答案 1 :(得分:1)
就行了
if($words[$i] == $common[$j]){
将其更改为
if(in_array($words[$i],$common)){
并删除第二个for循环。