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

Replacing words in a file, using another file in PHP

我有一个文件,上面有一段话 (Assignment2inputfile.txt)。我可以很好地打开那个文件。我有另一个文件(停用词),其中包含一个单词列表,如果在 Assignment2inputfile 中找到,则需要用单词 "stop" 替换(我在代码中将其全部大写,以便我可以立即看到它何时起作用).我觉得我正处于我需要的边缘,但替代并没有发生。这是一个练习,所以这就是为什么我的变量被命名得非常笼统或者用它们正在做的事情命名的原因(chng -> change -> changing the original file ; $new -> the result of the changes)

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

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 没有 return 新内容,it returns the number of bytes written to the file。因此,如果您想查看更改后的文本,只需 echo $chng; 而不是 $new.

这里我给你做个实战(未测试)

$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字界
  • ( ... | ... ) 是或

但是你想 trim 并预引用它们,这就是数组映射所做的。

如果您只是将所有单词替换为 'STOP',这应该没问题。

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

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

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