5

I want to use PHP to search through the contents of a file for an element with a specific id, replace its contents, then save my changes to the file. I'm able to load in the HTML, and save it back out again, but am having trouble with the 'find and replace' (currently trying to use preg_replace).

Here's what I have so far:

<?php
// read in the content
$file = file_get_contents('file.php');

// parse $file, looking for the id.
$replace_with = "id='" . 'myID' . "'>" . $replacement_content . "<";
if ($updated = preg_replace('/id\=\"myID\"\>.*?\</', $replace_with, $file)) {   
    // write the contents of $file back to index.php, and then refresh the page.
    file_put_contents('file.php', $updated);
}

However, while it successfully loads in the content and writes it out (I've tested it by writing to a separate file), it appears that $updated doesn't actually change.

Any ideas?

wallyk
  • 56,922
  • 16
  • 83
  • 148
Chris Armstrong
  • 3,585
  • 12
  • 42
  • 47
  • 1
    *(related)* [Best Methods to parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662) – Gordon Dec 03 '10 at 22:07

3 Answers3

11

You can use PHP's DOMDocument for this:

$html = new DOMDocument(); 
$html->loadHTMLFile('file.php'); 
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
karim79
  • 339,989
  • 67
  • 413
  • 406
1

just thinking why are you escaping "=", it should be /id=\"myID\"\>.*?\</

TomaszSobczak
  • 2,900
  • 21
  • 24
1

I think you have some escaping issues going on ;-)

try this:

$replace_with = 'id="myID">' . $replacement_content . '</';
if ($updated = preg_replace('#id="myID">.*?</#Umsi', $replace_with, $file)) {   
    // write the contents of $file back to index.php, and then refresh the page.
    file_put_contents('file.php', $updated);
}
Alex
  • 12,205
  • 7
  • 42
  • 52
  • That's the modifiers. U is for ungreedy, m is for multiline, s for including newlines and i for case insensitive. Have a look at the manual: http://php.net/manual/en/reference.pcre.pattern.modifiers.php – Alex Dec 04 '10 at 09:29
  • Is it true that with this solution the id must be at the end of the tag? And if so, is there a solution for elements with id's not matching this requirement? – Pepijn Gieles Aug 14 '14 at 08:18