簡體   English   中英

嘗試刪除HTML中的腳本標簽

[英]Trying to remove script tags in HTML

我正在嘗試使用PHP從HTML刪除腳本標簽,但是如果javascript中存在HTML,則無法使用。

例如,如果腳本標簽包含以下內容:

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

它將在</div>處停止,其余腳本仍將被考慮在內。

這是我一直用來刪除腳本標簽的內容:

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

一些基於正則表達式的預處理怎么樣?

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

?>

您可以使用strip_tags函數。 您可以在其中允許要允許的HTML屬性。

我認為這是“此時此地”的問題,您不需要任何特別的事情。 只是做這樣的事情:

$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_”的函數設置編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM