Roger
Roger

Reputation: 8576

PHP - find and replace in a file deleting the entire line where string is found with preg_replace

I am trying to make a find and replace operation in a file so that I erase the line where the string is found.

Here the contents of the sitemap.xml file:

<urlset>
<url><loc>http://ex.com/jane.htm</loc><lastmod>2013-10-23</lastmod></url>
<url><loc>http://ex.com/test.htm</loc><lastmod>2013-10-24</lastmod></url>
</urlset>`

This is what I got so far:

$x=preg_quote('test.htm');
preg_replace("/^.+$x.+\n/",'',file_get_contents('sitemap.xml'));

But it is not working...

Upvotes: 0

Views: 1003

Answers (2)

Michael Kunst
Michael Kunst

Reputation: 2988

As an alternative to using regex:

$fileContent = file_get_contents('sitemap.xml');
$stringToBeFound = 'test.htm';
$lines = explode("\n", $fileContent);
$result = array();
foreach($lines as $k => $line){
  if(strpos($line, $stringToBeFound) === false){
    $result[] = $line;
  }
}
echo implode("\n", $result);

Upvotes: 1

gwillie
gwillie

Reputation: 1899

Remove the ^ from your regex, eg:

/.+$x.+\n/

Upvotes: 1

Related Questions