PHP Regex to remove last paragraph and contents -
i have following stored in mysql table:
<p>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>this paragraph trying remove regex.</p></div>
i'm trying remove last paragraph tags , content on every row in table. can loop through table php enough, regex has me stumped.
every preg_match i've found on stackoverflow either gives me "preg_match(): unknown modifier" error, or var_dump shows empty array. believe match content if did work think need preg_replace?
the rows aren't identical in length, going last paragraph want remove.
would appreciate if show me how. thanks
this remove last <p>anything</p>
.
<?php $html = '<p>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>this paragraph trying remove regex.</p></div>'; $html = preg_replace('~(.*)<p>.*?</p>~', '$1', $html); echo $html;
the (.*)
grabbing until last paragraph tag , storing it. .*?
grabs between paragraph tags, ?
tells stop @ next closing paragraph tag. don't use capturing here because don't care inside. $1
found content before last <p>
. ~
delimiters telling regex begins , ends. suspect causing regexs fail currently. http://php.net/manual/en/regexp.reference.delimiters.php
output:
<p>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></div>
note: there xml/html parsers should consider using them because regexs html/xml can messy quickly.
http://php.net/manual/en/refs.xml.php
how parse , process html/xml in php?
demo: http://sandbox.onlinephpfunctions.com/code/0ddf46c328323e8b6357313a5464733ff797bc3f
Comments
Post a Comment