我有一个名为 $articleText
的变量它包含 html 代码。有script
和 style
<script>
内的代码和 <style>
html 元素。我想扫描 $articleText
并删除这些代码。如果我也可以删除实际的 html 元素 <script>
, </script>
, <style>
和 </style>
,我也会那样做。
我想我需要使用正则表达式,但我并不熟练。
有人可以帮忙吗?
我希望我能提供一些代码,但就像我说的,我不擅长正则表达式,所以我没有任何东西可以展示。
我不能使用 DOM。我需要特别针对这些特定标签使用正则表达式
最佳答案
不要在 HTML 上使用 RegEx。 PHP 提供了一个解析 DOM 结构的工具,适本地称为 DomDocument。
<?php
// some HTML for example
$myHtml = '<html><head><script>alert("hi mom!");</script></head><body><style>body { color: red;} </style><h1>This is some content</h1><p>content is awesome</p></body><script src="someFile.js"></script></html>';
// create a new DomDocument object
$doc = new DOMDocument();
// load the HTML into the DomDocument object (this would be your source HTML)
$doc->loadHTML($myHtml);
removeElementsByTagName('script', $doc);
removeElementsByTagName('style', $doc);
removeElementsByTagName('link', $doc);
// output cleaned html
echo $doc->saveHtml();
function removeElementsByTagName($tagName, $document) {
$nodeList = $document->getElementsByTagName($tagName);
for ($nodeIdx = $nodeList->length; --$nodeIdx >= 0; ) {
$node = $nodeList->item($nodeIdx);
$node->parentNode->removeChild($node);
}
}
您可以在这里尝试:https://eval.in/private/4f225fa0dcb4eb
文档
DomDocument
- http://php.net/manual/en/class.domdocument.phpDomNodeList
- http://php.net/manual/en/class.domnodelist.phpDomDocument::getElementsByTagName
- http://us3.php.net/manual/en/domdocument.getelementsbytagname.php
关于javascript - 删除脚本和样式标签中的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20082476/