我正在尝试使用PHP中的正则表达式替换我所拥有的模板HTML文件的一部分。到目前为止我有这个:
$docText = OLD_TEXT;
$text = NEW_TEXT;
$docText = preg_replace('#<div id="information">[<div>(?R)</div>]*</div>#i x U',
$text,
$docText,
1);
// Save file
此刻它没有进行任何比赛。目标是让它替换整个外部div,这意味着它需要知道所有其他s不是结束标记。
答案 0 :(得分:2)
我不确定你想要什么,但我认为你正在尝试这样做:
$html = <<<HTML
<html>
<head></head>
<body>
<div id="information">
<div>Hi!</div>
</div>
<div id="otherInformation">Hi again!</div>
</body>
</html>
HTML;
$replace = '<div id="newInformation">Bye!</div>';
$dom = new DOMDocument();
$dom->loadHTML($html);
$tmp = $dom->createTextNode('{newContent}');
$xpath = new DOMXPath($dom);
$divInformation = $xpath->query('//div[@id="information"]');
$divInformation->item(0)->parentNode->replaceChild($tmp, $divInformation->item(0));
$newHTML = str_replace('{newContent}', $replace, $dom->saveHTML());
var_dump($newHTML);
我可以问为什么吗?