如果.txt文件中存在单词,则PHP会更改整行

I'm using preg_replace to search for a word match within a line of a text file. If it is found, I would like to replace the entire line. My current problem is what I've tried thus far only replaces the exact word and not the entire line.

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.

EXPECTED OUTPUT

LOVING YOU MY FRIEND etc.
********
OFFENSIVEWORD2 YOU MY FRIEND etc.
OFFENSIVEWORD3 YOU MY FRIEND etc.

Thanks.

you need to change

$str = preg_replace("/\b".$id."\b/","********",$str);

to

$str = preg_replace("/\b" . $id . "\b.*
/ui", "********
", $str);

to make it work. Look out for the difference between newline among different operating systems.

update

or better use

$str = preg_replace("/.*\b" . $id . "\b.*
/ui", "********
", $str);

in case your offensive word is not in the start of the line.

This should do it as well (this is tested and works):

<?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>";

?>