如何从字符串中删除空的段落标签?
我遇到了WordPress模板的轻微编码问题.这是我在模板中使用的代码:
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(']]>', ']]>', $content);
$content = strip_tags($content, '<p><a><ul><li><i><em><strong>');
return $content;
}
?>
问题:我使用上面的代码从内容中剥离了标签,但是WordPress已经将图像标签放在段落中.因此结果是空段标记,其中图像被剥离.
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>
非常感谢! :)
使用此正则表达式删除空的段落
use this regex to remove empty paragraph
/<p[^>]*><\\/p[^>]*>/
示例
<?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>
?>