删除
我使用 DOMxpath 删除具有空文本节点的 html 标签,但保留
标签,
$xpath = new DOMXPath($dom);
while(($nodeList = $xpath->query('//*[not(text()) and not(node()) and not(self::br)]')) && $nodeList->length > 0)
{
foreach ($nodeList as $node)
{
$node->parentNode->removeChild($node);
}
}
它工作得很好,直到我遇到另一个问题,
$content = '<p><br/><br/><br/><br/></p>';
如何删除这种混乱的
和
?这意味着我不想允许
单独与
一起使用,但我允许
> 仅使用这样的正确文本,
$content = '<p>first break <br/> second break <br/> the last line</p>';
这可能吗?
还是用正则表达式更好?
我尝试过类似的操作,
$nodeList = $xpath->query("//p[text()=<br\s*\/?>\s*]");
foreach($nodeList as $node)
{
$node->parentNode->removeChild($node);
}
但它返回此错误,
Warning: DOMXPath::query() [domxpath.query]: Invalid expression in...
I use DOMxpath to remove html tags that have empty text node but to keep <br/>
tags,
$xpath = new DOMXPath($dom);
while(($nodeList = $xpath->query('//*[not(text()) and not(node()) and not(self::br)]')) && $nodeList->length > 0)
{
foreach ($nodeList as $node)
{
$node->parentNode->removeChild($node);
}
}
it works perfectly until I came across another problem,
$content = '<p><br/><br/><br/><br/></p>';
How do remove this kind of messy <br/>
and<p>
? which means I don't want to allow <br/>
alone with <p>
but I allow <br/>
with proper text like this only,
$content = '<p>first break <br/> second break <br/> the last line</p>';
Is that possible?
Or is it better with a regular expression?
I tried something like this,
$nodeList = $xpath->query("//p[text()=<br\s*\/?>\s*]");
foreach($nodeList as $node)
{
$node->parentNode->removeChild($node);
}
but it return this error,
Warning: DOMXPath::query() [domxpath.query]: Invalid expression in...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 XPath 选择不需要的 p:
注意 选择空文本节点,您不应该更好地使用 (?):
这将选择没有文本节点的任何元素(除了 br),例如:
或
包括。
You can select the unwanted p using XPath:
Note to select empty-text nodes shouldn't you better use (?):
This will select any element (but br) whithout text nodes, nodes like:
or
included.
我有几乎相同的情况,我使用:
并使用 urlencode() 将其改回以显示或插入数据库。
它对我有用。
I have almost same situation, i use:
And use
urlencode()
to change it back for display or inserting to database.Its work for me.
您可以通过简单地检查段落中是否只有空格和
标签来删除它们:preg_replace("\
; (\s|\
)*\<\/p\>","",$content);
分解:
不过,我会提到除非你的 HTML 是格式良好(一行,没有奇怪的空格或段落类等),您不应该使用正则表达式来解析它。如果是这样,这个正则表达式应该可以正常工作。
You could get rid of them all by simply checking to see that the only things within a paragraph are spaces and
<br />
tags:preg_replace("\<p\>(\s|\<br\s*\/\>)*\<\/p\>","",$content);
Broken down:
I will mention, however, that unless your HTML is well-formatted (one-line, no strange spaces or paragraph classes, etc), you should not use regex to parse this. If it is, this regex should work just fine.