1

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文件

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.

谢谢。

4

2 回答 2

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);

以防您的冒犯词不在行首。

于 2013-04-13T02:28:45.173 回答
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>";

?>
于 2013-04-13T02:50:07.823 回答