PHP Regex删除最后一段(具有属性)和内容


PHP Regex to remove last paragraph (having attributes) and contents

我的问题与Stackoverflow上的这个问题类似。但这是有区别的。

我在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"。如果最后一段具有此属性,则上述解决方案将删除不具有属性的内容的最后一段所以,我很难找到删除最后一段的方法,不管它的属性状态如何。

将正则表达式更改为:

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

Regex101演示

Regex突破

~           # 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)