如何在PHP中删除文本的html部分 [英] How to remove html part of a text in PHP
本文介绍了如何在PHP中删除文本的html部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对解析文本和删除不需要的html部分有疑问.我知道像-strip_tags()这样的函数会删除所有标签,但是问题是,该函数在那里保留了内部文本".
I have a question about parsing text and removing unwanted html parts. I know functions like - strip_tags() which will remove all the tags, but the problem is, that this function leaves the "inside text" there.
让我给你看一个例子,我们有一段文字:
Let me show you an example, we have a text:
Hello, how are you? <a href="">Link to my website</a> __Here continues html tags, links, images__
我要删除的是html所在的整个部分.不仅是标签,还包括文本(例如上面的链接到我的网站").
What I want is to remove the whole part, where html resides. Not only tags, but also text (like "Link to my website" above).
有什么有效的方法,功能我错过了吗?
Is there any efficient way, function that I missed?
推荐答案
尝试一下:
function removeTags($str) {
$result = '';
$xpath = new DOMXPath(DOMDocument::loadHTML(sprintf('<body>%s</body>', $str)));
foreach ($xpath->query('//body/text()') as $textNode) {
$result .= $textNode->nodeValue;
}
return $result;
}
echo removeTags(
'Hello, how are you? <a href="">Link to my website</a> __Here continues html <span>tags</span>, links, images__'
);
输出:
Hello, how are you? __Here continues html , links, images__
这篇关于如何在PHP中删除文本的html部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文