从 get_the_content() 中删除图像也会删除 <p>标签 [英] strip images from get_the_content() removes also <p> tags
本文介绍了从 get_the_content() 中删除图像也会删除 <p>标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码从 get_the_content()
中删除所有图像和周围的 标记:
I'm trying to strip all images and the surrounding <a>
tag from get_the_content()
with this piece of code:
<?php
$content = get_the_content();
$postOutput = preg_replace(array('{<a[^>]*><img[^>]+.}','{></a>}'),'', $content);
echo $postOutput;
?>
这很好用,除了段落周围没有 标签.
1. 使用get_the_content()
时是否正常?
2. 我怎样才能将它们添加到我的结果中?
3. 还是我的正则表达式错了?
That works fine, except there are no <p>
tags around the paragraphs.
1. Is this normal when using get_the_content()
?
2. and how could I add them to my result?
3. Or is my regex wrong?
推荐答案
好的,我会回答我自己的问题:
Okay I will answer my own questions:
- 是的,在
get_the_content()
上没有是正常的,谢谢@s_ha_dum
- 要添加
<p>
,我需要将内容过滤器应用为 此处提到(向下滚动到替代用法"). - 正则表达式没有错,但是对 html 进行正则表达式非常脏.谢谢@MarcB
- Yes it is normal that there are no
<p>
onget_the_content()
thanks @s_ha_dum - To add the
<p>
I need to apply the content filter as mentioned here (scroll down to "Alternative Usage"). - The regex is not wrong but it is pretty dirty to regex the html. Thanks @MarcB
查看导致以下代码的新问题 这里
See the new question that lead to the following code here
$dom = new DOMDocument;
$dom->loadHTML(get_the_content());
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//img|//a[img]');
foreach($nodes as $node) {
$node->parentNode->removeChild($node);
}
$no_image_content = $dom->saveHTML();
$no_image_content = apply_filters('the_content', $no_image_content);
$no_image_content = str_replace(']]>', ']]>', $no_image_content);
echo $no_image_content;
这篇关于从 get_the_content() 中删除图像也会删除 <p>标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文