jku*_*ner 9 html javascript php regex jquery
我有一个名为变量的变量$articleText,它包含html代码.有script和style内码<script>和<style>HTML元素.我想扫描$articleText并删除这些代码.如果我还可以删除实际的HTML元素<script>,</script>,<style>和</style>,我会做到这一点.
我想我需要使用正则表达式,但我不熟练.
有人可以帮忙吗?
我希望我能提供一些代码,但就像我说我不熟练的正则表达式,所以我没有任何东西可以显示.
Chr*_*ker 23
不要在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);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里试试: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Ωme*_*ega 22
即使正则表达式也不是这类任务的好工具,对于它可能起作用的小型简单任务.
如果您只想删除标签的内部文本,请使用:
preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "$1$3", $txt);
Run Code Online (Sandbox Code Playgroud)
在这里看演示.
如果你想删除标签,上面代码中的替换字符串将为空,所以只是"".
| 归档时间: |
|
| 查看次数: |
15003 次 |
| 最近记录: |