In PHP, how to remove wrapping paragraph, but only if it's the only paragraph
How to remove the (in this case, useless) wrapping paragraph in cases like this:
<p>Only paragraph</p>
开发者_运维技巧But to keep the string as it is when there is more than one paragraph involved:
<p>Paragraph 1</p>
<p>Paragraph 2</p>
preg_replace would probably do the trick in here but only if you can handle regexps.. :/
Here is one way, 2 test cases, $a and $b
$a = '<p>Only paragraph</p>';
$b = '<p>Only paragraph</p>
<p>Only paragraph</p>
<p>Only paragraph</p>';
// change the values to $a and then $b
if( count( explode('<p>', $a) ) == 2 ){
$c = preg_replace('#</?p>#', '', $a);
}
if( isset( $c)) {
var_dump( $c );
}
// 'Only paragraph'
You might need to add a trim() first as well.
Does not cater for malformed input eg
<p>para1 </p> para 2</p>
精彩评论