我想使用 PHP 在文件的内容中搜索具有特定 id 的元素,替换其内容,然后将更改保存到文件中。我能够加载 HTML,并再次将其保存回来,但在“查找和替换”(当前正在尝试使用 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 似乎实际上并没有改变。
有任何想法吗?