Filipino Autoliker
Filipino Autoliker

Reputation: 25

PHP change whole line if a word exist in a line of .txt file

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.

Upvotes: 1

Views: 1411

Answers (2)

Zack
Zack

Reputation: 1703

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

?>

Upvotes: 0

Ejaz
Ejaz

Reputation: 8872

you need to change

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

to

$str = preg_replace("/\b" . $id . "\b.*\n/ui", "********\n", $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.*\n/ui", "********\n", $str);

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

Upvotes: 4

Related Questions