javascript - 删除脚本和样式标签中的所有内容

标签 javascript php jquery html regex

我有一个名为 $articleText 的变量它包含 html 代码。有scriptstyle <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

文档

关于javascript - 删除脚本和样式标签中的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20082476/

相关文章:

javascript - fast-xml-parser 认为结束标签在没有结束括号的情况下也是有效的

javascript - 在排序列表周围包装 div

php - 用 JavaScript 实现 PHP 字符串异或

php - 易2 : Unable to create a relation with a condition about the related table

jQuery:单击按钮,单击事件触发两次或多次

javascript - 将自动化浏览器脚本制作成node.js

javascript - 使用 async/await 时调用堆栈的工作

javascript - Woocommerce 变体

javascript - jQuery 过滤

javascript - 并排显示选择框中的两个选项