0

我正在尝试使用 PHP 从 HTML 中删除脚本标签,但如果 javascript 中有 HTML,它就不起作用。

例如,如果脚本标签包含如下内容:

function tip(content) {
        $('<div id="tip">' + content + '</div>').css

它将停止,</div>脚本的其余部分仍将被考虑在内。

这是我用来删除脚本标签的方法:

foreach ($doc->getElementsByTagName('script') as $node)
{
    $node->parentNode->removeChild($node);
}
4

3 回答 3

0

一些基于正则表达式的预处理怎么样?

示例input.html

<html>
  <head>
    <title>My example</title>
  </head>
  <body>
    <h1>Test</h1>
    <div id="foo">&nbsp;</div>
    <script type="text/javascript">
      document.getElementById('foo').innerHTML = '<span style="color:red;">Hello World!</span>';
    </script>
  </body>
</html>

脚本标签删除 php 脚本:

<?php

    // unformatted source output:
    header("Content-Type: text/plain");

    // read the example input file given above into a string:
    $input = file_get_contents('input.html');

    echo "Before:\r\n";
    echo $input;
    echo "\r\n\r\n-----------------------\r\n\r\n";

    // replace script tags including their contents by ""
    $output = preg_replace("~<script[^<>]*>.*</script>~Uis", "", $input);

    echo "After:\r\n";
    echo $output;
    echo "\r\n\r\n-----------------------\r\n\r\n";

?>
于 2013-02-09T22:53:28.680 回答
0

你可以使用strip_tags函数。您可以在其中允许HTML您希望允许的属性。

于 2015-08-03T07:04:47.830 回答
0

我认为这是“此时此地”的问题,你不需要什么特别的东西。只需执行以下操作:

$text = file_get_content('index.html');
while(mb_strpos($text, '<script') != false) {
$startPosition = mb_strpos($text, '<script');
$endPosition = mb_strpos($text, '</script>');
$text = mb_substr($text, 0, $startPosition).mb_substr($text, $endPosition + 7, mb_strlen($text));
}
echo $text;

只为类似“mb_”的函数设置编码

于 2015-08-03T07:16:20.287 回答