按id查找元素并用php替换其内容

时间:2010-12-03 21:45:32

标签: php html preg-replace replace savechanges

我想使用PHP在文件内容中搜索具有特定id的元素,替换其内容,然后将我的更改保存到文件中。我可以加载HTML,然后再将其保存回来,但是我遇到了'find and replace'(目前正在尝试使用preg_replace)的问题。

这是我到目前为止所拥有的:

<?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);
}

然而,虽然它成功加载了内容并将其写出来(我已经通过写入单独的文件对其进行了测试),但似乎$ updated实际上并没有改变。

有什么想法吗?

3 个答案:

答案 0 :(得分:10)

您可以使用PHP的DOMDocument

$html = new DOMDocument(); 
$html->loadHTMLFile('file.php'); 
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");

答案 1 :(得分:1)

只是想到你为什么要逃避“=”,它应该是/id=\"myID\"\>.*?\</

答案 2 :(得分:1)

我认为你有一些逃避问题;-)

试试这个:

$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);
}