自动从HTML中删除“p”标记

时间:2013-08-22 16:41:42

标签: php wordpress

我有以下代码,据说会删除所有缠绕在图像周围的p标记。我实际上正在复制并将其粘贴到我的functions.php中。但是,它不起作用:

function filter_ptags_on_images($content){
   return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}

add_filter('the_content', 'filter_ptags_on_images');

我是否需要使用与我的主题更相关的内容更改函数参数?我是WordPress的新手,所以对于看似愚蠢的问题道歉。

4 个答案:

答案 0 :(得分:1)

您可以通过在functions.php中添加此代码来禁用此功能

remove_filter( 'the_content', 'wpautop' );  // Disable auto 'p' in content

remove_filter( 'the_excerpt', 'wpautop' ); // Disable auto 'p' in excerpt

remove_filter()

wpautop

答案 1 :(得分:0)

这不会起作用吗?

function filter_ptags_on_images($content){
   return preg_replace('/\<p\b.*?\>(.+)\<\/p\>/i', '$1', $content);
}

编辑:

我的不好,对不起,我没有仔细阅读

function filter_ptags_on_images($content){
   if (!preg_match_all('/\<p\b.*?\>(.+?)\<\/p\>/is',$content,$ps)) {
      return $content;
   }

   $new_content = $content;

   foreach ($ps[0] as &$p) {
      if (strpos($p,"<img ")) {
         $p_stripped_chunk = preg_replace('/\<p\b.*?\>(.*?\<img\b.+\>.*?)\<\/p\>/is', '$1', $p);
         $new_content = str_replace($p,$p_stripped_chunk,$new_content);
      }
   }

   return $new_content;
}

编辑:

这是我认为的另一个更好的版本:

function filter_ptags_on_images($content){
   if (!preg_match_all('/\<p\b.*?\>(.*?)\<\/p\>/is',$content,$ps_with_image)) {
      return $content;
   }

   foreach ($ps_with_image[0] as $match_x => $p) {
      if (!stripos($p,'<img')) {
         unset($ps_with_image[0][$match_x],$ps_with_image[1][$match_x]);
      }
   }

   return str_replace($ps_with_image[0], $ps_with_image[1], $content);
}

编辑:

这是更好的版本:

function filter_ptags_on_images($content){
   if (!preg_match_all('/\<p\b[^\>]*?\>(([^\<]|\<(?!\/p))*?\<img\b.+?\>.*?)\<\/p\>/is',$content,$ps_with_image)) {
      return $content;
   }
   return str_replace($ps_with_image[0], $ps_with_image[1], $content);
}

答案 2 :(得分:0)

var context = $("p > img");

for (var i = 0; i < context.length; i++) {
    $(context[i]).remove();
}

这将删除图片周围的所有<p>标记及其内容。

答案 3 :(得分:0)

从图片和iFrame过滤P标签

function filter_ptags_on_images($content)
{
$content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
}
add_filter('the_content', 'filter_ptags_on_images');
相关问题