duanshan2988 2011-07-26 23:38
浏览 154
已采纳

使用DOMxpath或regex删除<p> <br/> </ p>?

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...
  • 写回答

3条回答 默认 最新

  • drbxr86044 2011-07-27 09:48
    关注

    You can select the unwanted p using XPath:

    "//p[count(*)=count(br) and br and normalize-space(.)='']"
    

    Note to select empty-text nodes shouldn't you better use (?):

    "//*[normalize-space(.)='' and not(self::br)]"
    

    This will select any element (but br) whithout text nodes, nodes like:

    <p><b/><i/></p>
    

    or

    <p> <br/>   <br/>
    </p>
    

    included.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么