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

按id查找元素并用php替换其内容,php,html,preg-replace,replace,savechanges,Php,Html,Preg Replace,Replace,Savechanges,我想使用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'

我想使用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);
}

想想你为什么要转义“=”,它应该是
/id=\“myID\”\>。?\你可以使用PHP来实现这一点:

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

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

试试这个:

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

$replace_为='id=“myID”>'$替换内容。“*?谢谢我不能用这种方式将其保存为php文件吗?将来也有可能是xml文件。你可以,但我不认为这有什么意义,因为输出仍然是HTML。它现在需要是php才能在其他地方使用。谢谢,尝试了这个,它工作得很好,对我来说也简单得多!(相关)这就是修饰符。U表示ungreedy,m表示multiline,s表示包含换行符,i表示不区分大小写。请看一下手册:使用此解决方案时,id是否必须位于标记的末尾?如果是这样,对于id不符合此要求的元素是否有解决方案?