1

I have this function:

<?php

$post="marie" . "\n"; // \n not working?

//replace txt
$oldMessage = $post;
$deletedFormat = "";

//read the entire string
$str=file_get_contents('log.txt');

//replace something in the file string - this is a VERY simple example
$str=str_replace("$oldMessage", "$deletedFormat",$str);

//write the entire string
file_put_contents('log.txt', $str);

?>

I want to find marie and replace it:

ANAff
marieb
marie
mariec
marie

So it should replace only the 3 one, but the result was:

ANAff
b

c

In other words, I want to remove the exactly $post value from log.txt. how to do this? And if possible, how to remove the full line? not let it blank.

RGS
  • 4,062
  • 4
  • 31
  • 67

1 Answers1

1

Try the following code

echo preg_replace('/marie\b/', '', $str);
Andrej
  • 7,474
  • 1
  • 19
  • 21
  • nice! sometimes I have urls too, like: `http://www.stac`... instead of marie I put this URL and it is not working. maybe because the http:`//` ? – RGS Aug 27 '16 at 18:03
  • 1
    Yes, you have to escape all special chars like \/ – Andrej Aug 27 '16 at 18:04
  • No, because htmlspecialchars is for html rendering. Look at http://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript – Andrej Aug 27 '16 at 18:08