我正在使用preg_replace
在文本文件的一行中搜索单词匹配。如果找到了,我想替换整行。我目前的问题是我到目前为止所尝试的只是替换了确切的单词,而不是整行。
PHP
$database = "1.txt";
$id = "OFFENSIVEWORD1";
$str = file_get_contents($database);
$str = preg_replace("/\b".$id."\b/","********",$str);
$fp = fopen($database,'w');
fwrite($fp,$str);
fclose($fp);
1.TXT FILE
LOVING YOU MY FRIEND etc.
OFFENSIVEWORD1 YOU MY FRIEND etc.
OFFENSIVEWORD2 YOU MY FRIEND etc.
OFFENSIVEWORD3 YOU MY FRIEND etc.
预期输出
LOVING YOU MY FRIEND etc.
********
OFFENSIVEWORD2 YOU MY FRIEND etc.
OFFENSIVEWORD3 YOU MY FRIEND etc.
感谢。
答案 0 :(得分:4)
你需要改变
$str = preg_replace("/\b".$id."\b/","********",$str);
到
$str = preg_replace("/\b" . $id . "\b.*\n/ui", "********\n", $str);
让它发挥作用。请注意不同操作系统中换行符之间的区别。
或更好地使用
$str = preg_replace("/.*\b" . $id . "\b.*\n/ui", "********\n", $str);
万一你的冒犯性词不在行的开头。
答案 1 :(得分:0)
这也应该这样做(这是经过测试和运作的):
<?PHP
$str = "
hello this is PROFANE 1
clean statement";
$lines = explode('
', $str);
$newfile = '';
foreach($lines as $line) {
// ** change PROFANE 1 and PROFANE 2 obviously to real profane words to filter out
if (stripos($line, 'PROFANE 1') !== false || stripos($line, 'PROFANE 2') !== false) {
$line = preg_replace("/./", "*", $line);
}
$newfile .= '
' . $line;
}
echo "<pre>" . $newfile . "</pre>";
?>