Search code examples
phphtmlpurifiersubstrstrip-tags

PHP: Strip Wrapping Paragraph Tags


I need to write a PHP function which removes opening and closing paragraph tags from a string, but only if they are at the very beginning/end. So the strings:

"Simple Test"
"<p>Here</p>"
"<p>Test <p>Nested</p> Outside </p>"

Would Output:

"Simple Test"
"Here"
"Test <p>Nested</p> Outside"

Can HTMLPurifier do this or should I use substr? My first attempt was:

if(strpos($str,'<p>') === 0  && strcmp(substr($str,-1,4),'</p>'))
$str = substr($str,3,strlen($str)-4);

Solution

  • This is a regex solution:

    $str = preg_replace('!^<p>(.*?)</p>$!i', '$1', $str);