【问题标题】:Trying to remove script tags in HTML尝试删除 HTML 中的脚本标签
【发布时间】:2013-02-09 20:35:43
【问题描述】:

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

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

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

它将在&lt;/div&gt; 停止,脚本的其余部分仍将被考虑在内。

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

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

【问题讨论】:

  • 请注意,PHP 是一种服务器端语言,因此如果您在页面加载后尝试删除脚本标签,它不会做任何事情
  • 你在使用 DOMDocument 吗?
  • 这是一个javascript模板吗?如果是这样,您不能使用 DomDocument 执行此操作。试试html5lib
  • 是的,我正在使用 DOMDocument,一切正常,除非脚本标签中有

标签: php javascript html dom tags


【解决方案1】:

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

例如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";

?>

【讨论】:

  • 奇怪的是,它仍然停在&lt;/div&gt;
  • @Alex 你能提供一些细节吗?对我来说,它还删除了所有包含 div 的脚本标签。
  • 我做了一些编辑,现在可以了。谢谢你的帮助。 :)
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    $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_”类函数设置编码

    【讨论】:

      猜你喜欢
      • 2017-02-27
      • 1970-01-01
      • 2011-10-31
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 2017-02-09
      • 2016-01-30
      相关资源
      最近更新 更多