尝试删除HTML中的脚本标记

时间:2013-02-09 20:35:43

标签: php javascript html dom tags

我正在尝试使用PHP从HTML中删除脚本标记,但如果javascript中有HTML,则无效。

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

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

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

这是我一直用来删除脚本标记的内容:

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

3 个答案:

答案 0 :(得分: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";

?>

答案 1 :(得分:0)

您可以使用strip_tags功能。您可以在其中允许您希望允许的HTML属性。

答案 2 :(得分:0)

我认为这是现在和现在的&#39;问题,你不需要特别的东西。做这样的事情:

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

仅为&#39; mb _&#39;设置编码喜欢的功能