gpt4 book ai didi

php - DOMDocument 删除脚本标签中的结束标签

转载 作者:行者123 更新时间:2023-12-05 00:41:29 26 4
gpt4 key购买 nike

我有以下 test.php文件,当我运行它时,关闭 </h1>标签被删除。

<?php

$doc = new DOMDocument();

$doc->loadHTML('<html>
<head>
<script>
console.log("<h1>hello</h1>");
</script>
</head>
<body>

</body>
</html>');

echo $doc->saveHTML();

这是我执行文件时的结果:

PHP Warning:  DOMDocument::loadHTML(): Unexpected end tag : h1 in Entity, line: 4 in /home/ryan/NetBeansProjects/blog/test.php on line 14

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<script>
console.log("<h1>hello");
</script>
</head>
<body>
</body>
</html>

那么,为什么要删除标签?它是一个字符串,所以它不应该忽略它吗?

最佳答案

想到的唯一解决方案是预先匹配脚本标签,然后将它们替换为临时持有者,如 <script id="myuniqueid"></script>并在 dom 管理结束时再次替换为实际脚本,如下所示:

//  The dom doc
$doc = new DOMDocument();

// The html
$html = '<html>
<head>
<script>
console.log("<h1>hello</h1>");
</script>
</head>
<body>

</body>
</html>';

// Patter for scripts
$pattern = "/<script([^']*?)<\/script>/";
// Get all scripts
preg_match_all($pattern, $html, $matches);

// Only unique scripts
$matches = array_unique( $matches[0] );

// Construct the arrays for replacement
foreach ( $matches as $match ) {
// The simple script
$id = uniqid('script_');
$uniqueScript = "<script id=\"$id\"></script>";
$simple[] = $uniqueScript;
// The complete script
$complete[] = $match;
}

// Replace the scripts with the simple scripts
$html = str_replace($complete, $simple, $html);
// load the html into the dom
$doc->loadHTML( $html);

// Do the dom management here
// TODO: Whatever you do with the dom

// When finished
// Get the html back
$html = $doc->saveHTML();
// Replace the scripts back
$html = str_replace($simple, $complete, $html);
//Print the result
echo $html;

此解决方案打印干净,没有 dom 错误。

关于php - DOMDocument 删除脚本标签中的结束标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com