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

2021-12-25 00:00:00 replace php html preg-replace savechanges

我想使用 PHP 在文件内容中搜索具有特定 ID 的元素,替换其内容,然后将更改保存到文件中.我能够加载 HTML,然后再次将其保存,但是在查找和替换"(目前正在尝试使用 preg_replace)时遇到问题.

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).

这是我目前所拥有的:

<?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 实际上并没有改变.

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.

有什么想法吗?

推荐答案

你可以使用 PHP 的 DOMDocument 为此:

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

相关文章