Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty paragraph tags from string?

Tags:

php

I ran into a slight coding problem with WordPress template. This is the code I use in template:

<?php echo teaser(40); ?> 

In my functions, I use this to strip tags and get content from allowed tags only.

<?php function teaser($limit) {     $content = explode(' ', get_the_content(), $limit);     if (count($content)>=$limit) {     array_pop($content);     $content = implode(" ",$content).'...';     } else {     $content = implode(" ",$content);     }        $content = preg_replace('/\[.+\]/','', $content);     $content = apply_filters('the_content', $content);      $content = str_replace(']]>', ']]&gt;', $content);     $content = strip_tags($content, '<p><a><ul><li><i><em><strong>');     return $content; } ?> 

The problem: I use the above code to strip tags from the content, but WordPress already puts image tags within paragraph. So the result is empty paragraph tags where images are stripped.

Just for the sake of cleaning up my code and useless empty tags. My question is how to remove empty paragraph tags?

<p></p> 

Thanks a lot in advance! :)

like image 597
Ahmad Fouad Avatar asked Sep 28 '10 01:09

Ahmad Fouad


People also ask

How do I remove the blank P tag?

* Removes empty paragraph tags from shortcodes in WordPress. add_filter( 'the_content' , 'tg_remove_empty_paragraph_tags_from_shortcodes_wordpress' ); That's it! All empty paragraph tags have been removed from your shortcodes.

Is paragraph tag empty?

Yes you have to use the Empty paragraph tags in HTML editor.


2 Answers

use this regex to remove empty paragraph

/<p[^>]*><\\/p[^>]*>/ 

example

<?php $html = "abc<p></p><p>dd</p><b>non-empty</b>";  $pattern = "/<p[^>]*><\\/p[^>]*>/";  //$pattern = "/<[^\/>]*>([\s]?)*<\/[^>]*>/";  use this pattern to remove any empty tag  echo preg_replace($pattern, '', $html);  // output //abc<p>dd</p><b>non-empty</b> ?> 
like image 147
Pramendra Gupta Avatar answered Oct 13 '22 08:10

Pramendra Gupta


This gets rid of all empty p tags, even if they contain spaces or &nbps; inside.

$str = "<p>  </p><p> &nbsp; </p><p>&nbsp</p><p>Sample Text</p>";  echo preg_replace("/<p[^>]*>(?:\s|&nbsp;)*<\/p>/", '', $str); 

This only echoes <p>Sample Text</p>

like image 28
Malitta N Avatar answered Oct 13 '22 10:10

Malitta N