2016-12-27 115 views
-1

我有以下代码,它可以提取blockquote并将我的WordPress帖子内容放入<p>标签中。从段落标签中删除图片

<?php 
    $content = preg_replace('/<blockquote>(.*?)<\/blockquote>/', '', get_the_content()); 
    $content = wpautop($content); // Add paragraph-tags 
    $content = str_replace('<p></p>', '', $content); // remove empty paragraphs 
    echo $content; 
?> 

但是它把图像中,我不想

+0

1.你想做什么? 2.你是否尝试自己写点东西? 3.输出是怎样的? – Dekel

+0

您可能需要为图像运行另一个'''preg_replace'''。 [Here](http://wordpress.stackexchange.com/questions/7090/stop-wordpress-wrapping-images-in-a-p-tag)是一个模式的例子。 – CUGreen

回答

1

这里<p>标签是一些代码,应该这样做(未测试)。

<?php 
    $content = preg_replace('/<blockquote>(.*?)<\/blockquote>/', '', get_the_content()); 
    $content = wpautop($content); // Add paragraph-tags 
    $content = str_replace('<p></p>', '', $content); // remove empty paragraphs 
    $content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); // remove paragraphs around img tags 
    echo $content; 
?> 
+0

似乎工作谢谢你!我知道很多人说不要使用pregreplace – user3550879

+0

也许是因为代码注入的危险,不确定。 – CUGreen

0

str_replace后的线,你可以使用这个domDocument方法:

$dom = new domDocument; 
$dom->loadHTML($content); 
$dom->preserveWhiteSpace = false; 
$images = $dom->getElementsByTagname('img'); 
$removeList = array(); 
foreach ($images as $domElement) { 
    $removeList[] = $domElement; 
} 
foreach ($removeList as $toRemove) { 
    $toRemove->parentNode->removeChild($toRemove); 
} 
$content = $dom->saveHTML(); 

(PS:这也会给你一个非preg_replace方法,而不是它真正的问题)

+0

我似乎从来没有把domDocuments,他们似乎总是抛出错误或只是不工作 – user3550879

+0

我一直在使用上述多年。零错误总是有效的。没有复杂的'preg_replace()'。 – Abela

+0

哦,好吧,那就是我的结局。我通常只是将这些类型的代码放在标签中 – user3550879