問題描述
我想使用 PHP 在文件內(nèi)容中搜索具有特定 ID 的元素,替換其內(nèi)容,然后將更改保存到文件中.我能夠加載 HTML,然后再次將其保存,但是在查找和替換"(目前正在嘗試使用 preg_replace)時(shí)遇到問題.
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);
}
然而,雖然它成功加載內(nèi)容并將其寫出(我已經(jīng)通過寫入單獨(dú)的文件對(duì)其進(jìn)行了測試),但似乎 $updated 實(shí)際上并沒有改變.
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");
這篇關(guān)于通過 id 查找元素并用 php 替換其內(nèi)容的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!