[英]Trying to remove script tags in HTML
I am trying to remove script tags from HTML using PHP but it doesn't work if there's HTML inside the javascript. 我正在尝试使用PHP从HTML删除脚本标签,但是如果javascript中存在HTML,则无法使用。
For example, if the script tags contain something like this: 例如,如果脚本标签包含以下内容:
function tip(content) {
$('<div id="tip">' + content + '</div>').css
It will stop at </div>
and the rest of the script will still be taken into account. 它将在</div>
处停止,其余脚本仍将被考虑在内。
This is what I have been using to remove the script tags: 这是我一直用来删除脚本标签的内容:
foreach ($doc->getElementsByTagName('script') as $node)
{
$node->parentNode->removeChild($node);
}
How about some regex-based pre-processing? 一些基于正则表达式的预处理怎么样?
Example input.html
: 示例input.html
:
<html>
<head>
<title>My example</title>
</head>
<body>
<h1>Test</h1>
<div id="foo"> </div>
<script type="text/javascript">
document.getElementById('foo').innerHTML = '<span style="color:red;">Hello World!</span>';
</script>
</body>
</html>
Script tag removing php script: 脚本标记删除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";
?>
You can use strip_tags
function. 您可以使用strip_tags
函数。 In which you can allow the HTML
attributes which you want allowed. 您可以在其中允许要允许的HTML
属性。
I think this is 'here and now' problem, and you need no something special. 我认为这是“此时此地”的问题,您不需要任何特别的事情。 Just do something like this: 只是做这样的事情:
$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;
Only set encoding for 'mb_' like functions 仅为类似“ mb_”的函数设置编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.