簡體   English   中英

去掉 <p><br/></p> 與DOMxpath或正則表達式?

[英]Remove <p><br/></p> with DOMxpath or regex?

我使用DOMxpath刪除了具有空文本節點但保留<br/>標記的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>'; 

如何刪除這種凌亂的<br/><p> 這意味着我不想只允許<br/><p>但是我允許<br/>僅帶有這樣的適當文本,

$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...

您可以使用XPath選擇不需要的p:

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

請注意 ,選擇空文本節點不應該更好地使用(?):

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

這將選擇沒有文本節點的任何元素(但不包括br),這些節點如:

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

要么

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

包括在內。

我有幾乎相同的情況,我使用:

$document->loadHTML(str_replace('<br>', urlencode('<br>'), $string_or_file));

並使用urlencode()將其更改回顯示或插入數據庫。 它為我工作。

您只需檢查段落中唯一的內容就是空格和<br />標記,就可以擺脫它們: preg_replace("\\<p\\>(\\s|\\<br\\s*\\/\\>)*\\<\\/p\\>","",$content);

細分:

\<p\>    # Match for <p>
(        # Beginning of a group
  \s       # Match a space character
  |        # or...
  \<br\s*\/\> # match a <br /> tag, with any number (including 0) spaces between the <br and />
)*       # Match this whole group (spaces or <br /> tags) 0 or more times.
\<\/p\>  # Match for </p>

但是,我要提到的是,除非您的HTML格式正確(單行,沒有奇怪的空格或段落類,等等),否則您不應使用正則表達式來對此進行解析。 如果是這樣,則此正則表達式應該可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM