使用PHP中的另一个文件替换文件中的单词

时间:2018-10-04 21:31:26

标签: php str-replace

我有一个带有段落的文件(Assignment2inputfile.txt)。我可以打开那个文件。我还有另一个文件(停用词),其中包含一个单词列表,如果在Assignment2inputfile中找到该单词,则需要将其替换为“停止”(我将其放在代码的所有大写字母中,以便可以在工作时立即看到)。我感觉自己就在需要的边缘,但是替换没有发生。这是一个练习,所以这就是为什么我的变量的命名非常笼统或使用它们的作用(chng-> change->更改原始文件; $ new->更改的结果)

$x = file_get_contents('Assignment2inputfile.txt');
$chng = str_replace("stopwords",'STOP', $x); 
$new = file_put_contents('Assignment2inputfile.txt', $chng);
echo $new; 

2 个答案:

答案 0 :(得分:0)

str_replace可以将字符串数组作为第一个参数,它将查找并替换目标字符串中的每个字符串。所以在这里

$chng = str_replace("stopwords", 'STOP', $x);

"stopwords"必须是包含该文件中单词列表的数组$stopwords

获取该数组的最简单方法可能是使用file,该函数将文件读入数组。

$stopwords = file('stopwords.txt', FILE_IGNORE_NEW_LINES);
$chng = str_replace($stopwords, 'STOP', $x);

FILE_IGNORE_NEW_LINES是必需的,因为否则数组中的字符串将包含换行符,因此可能与其他文件中的任何内容都不匹配。


旁注的排序,但file_put_contents不返回新内容it returns the number of bytes written to the file。因此,如果您想查看更改后的文本,只需echo $chng;而不是$new

答案 1 :(得分:-1)

在这里,我会为您做个扎实的(未试的)

$x = file_get_contents('Assignment2inputfile.txt');

//if file returns false we cant use a boolean as an array, so this is more sensable
if(false === ($stopwords = file('stopwords.txt', FILE_SKIP_EMPTY_LINES))) throw new Exception('Could not load stop words from file');

$stopwords = array_map(function($item){
    return preg_quote(trim($item),'/');
}, $product);
$pattern = '/\b('.implode('|', $stopwords).')\b/';

$chng = preg_replace($pattern, 'STOP', $x); 
$new = file_put_contents('Assignment2inputfile.txt', $chng);

基本上,在过滤了停用词(数组)之后,您会得到这样的模式

/\b(the|and|for)\b/

模式基本上是

  • \b单词边界
  • ( ... | ... )是OR

但是您想修剪并预引用它们,这就是数组映射的作用。

如果您只是用“ STOP”代替所有单词,那应该没问题。

http://php.net/manual/en/function.file.php

http://php.net/manual/en/function.preg-quote.php

哦和'stopwords.txt'应该是停用词文件的名称。