【发布时间】:2010-04-13 14:09:57
【问题描述】:
我怎样才能剥离<h1>including this content</h1>
我知道您可以使用条形标签来删除标签,但我希望两者之间的所有内容都消失。
任何帮助将不胜感激。
【问题讨论】:
标签: php
我怎样才能剥离<h1>including this content</h1>
我知道您可以使用条形标签来删除标签,但我希望两者之间的所有内容都消失。
任何帮助将不胜感激。
【问题讨论】:
标签: php
在处理 HTML 时,您应该使用 HTML 解析器来正确处理它。你可以使用 PHP 的 DOMDocument 并使用 DOMXPath 查询元素,例如:
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//h1') as $node) {
$node->parentNode->removeChild($node);
}
$html = $doc->saveHTML();
【讨论】:
$xpath->query('//h1//script//div') 之类的东西?
$xpath->query('//h1|//script|//div')
试试这个:
preg_replace('/<h1[^>]*>([\s\S]*?)<\/h1[^>]*>/', '', '<h1>including this content</h1>');
示例:
echo preg_replace('/<h1[^>]*>([\s\S]*?)<\/h1[^>]*>/', '', 'Hello<h1>including this content</h1> There !!');
输出:
Hello There
【讨论】:
>。
如果您想去除所有标签并包括内容:
$yourString = 'Hello <div>Planet</div> Earth. This is some <span class="foo">sample</span> content!';
$regex = '/<[^>]*>[^<]*<[^>]*>/';
echo preg_replace($regex, '', $yourString);
#=> Hello Earth. This is some content!
HTML 属性可以包含< 或>。因此,如果您的 HTML 变得过于混乱,此方法将不起作用,您将需要一个 DOM 解析器。
NODE EXPLANATION
--------------------------------------------------------------------------------
< '<'
--------------------------------------------------------------------------------
[^>]* any character except: '>' (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
> '>'
--------------------------------------------------------------------------------
[^<]* any character except: '<' (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
< '<'
--------------------------------------------------------------------------------
[^>]* any character except: '>' (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
> '>'
【讨论】:
>。
您可以使用 XSLT 样式表并将所有标签与它们自己匹配,除了 h1 标签,它会与空字符串匹配,然后将其应用于您的文档。不过做这么简单的事情可能有点太重了。
【讨论】:
您还可以使用 strip_tags 删除标签以及介于两者之间的所有内容..
$html 包含您要从中删除标签的 html 或 php。
strip_tags($html,"");
试试这个,我认为这对你有用。
【讨论】: