2016-01-02 35 views
1

我的問題類似於this在Stackoverflow上問的問題。但是有一個區別。PHP正則表達式刪除最後一段(有屬性)和內容

,我有以下存儲在MySQL表:

<p align="justify">First paragraph</p> 
<p>Second paragraph</p> 
<p>Third paragraph</p> 
<div class="item"> 
<p>Some paragraph here</p> 
<p><strong><u>Specs</u>:</strong><br /><br /><strong>Weight:</strong> 10kg<br /><br /><strong>LxWxH:</strong> 5mx1mx40cm</p 
<p align="justify">second last para</p> 
<p align="justify">This is the paragraph I am trying to remove with regex.</p> 
</div> 

我試圖刪除最後一個段落標記和內容表中的每一行。在鏈接的問題中提到的最佳答案建議下面的正則表達式 -

preg_replace('~(.*)<p>.*?</p>~', '$1', $html) 

從鏈接的問題不同的是 - 有時我的最後一個段落標記可以(或可能不會)有屬性align="justify"。如果最後一個段落具有此屬性,則提到的解決方案將刪除不具有屬性的內容的最後一段。因此,我正在努力尋找一種方法來刪除最後一段,而不管它的屬性狀態如何。

+0

[除XHTML自足標籤的正則表達式匹配開放標籤](可能的重複HTTP ://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-包含標籤) –

+0

@LucasTrzesniewski感謝您的鏈接。雖然我完全不理解它,但我已將它加入書籤。 –

+1

鏈接基本上說你應該使用正確的工具來完成這項工作。這裏需要一個HTML解析器/ DOM操作庫。使用正則表達式很脆弱 - 使用DOM(或XPath或CSS選擇器)可以更好,更輕鬆地完成。 –

回答

1

變化的正則表達式:

preg_replace('~(.*)<p[^>]*>.*</p>\R?~s', '$1', $html) 

Regex101 Demo

正則表達式突圍

~   # Opening regex delimiter 
    (.*)  # Select any chars matching till the last '<p>' tags 
      # (actually it matches till the end then backtrack) 
    <p[^>]*> # select a '<p>' tag with any content inside '<p .... >' 
      # the content chars after '<p' must not be the literal '>' 
    .*  # select any char till the '</p>' closing tag 
    </p>  # matches literal '</p>' 
    \R?  # select (to remove it) any newline (\r\n, \r, \n) 
~s   # Closing regex delimiter with 's' DOTALL flag 
      # (with 's' the '.' matches also newlines) 
+0

謝謝。有效。我認爲你需要編輯答案,並從正則表達式中刪除這些文本=> **強烈的文本** –

+0

@ Dr.AtulTiwari:謝謝,奇怪的是它發生在我貼東西的時候! –

相關問題