【问题标题】:strip images from get_the_content() removes also <p> tags从 get_the_content() 中删除图像也删除 <p> 标签
【发布时间】:2013-01-30 10:51:35
【问题描述】:

我正在尝试使用这段代码从get_the_content() 中删除所有图像和周围的&lt;a&gt; 标签:

<?php
$content = get_the_content();
$postOutput = preg_replace(array('{<a[^>]*><img[^>]+.}','{></a>}'),'', $content);
echo $postOutput;
?>

效果很好,只是段落周围没有&lt;p&gt; 标签。
1.使用get_the_content()时这样正常吗?
2. 如何将它们添加到我的结果中?
3. 还是我的正则表达式错了?

【问题讨论】:

  • 错错错了。不要使用正则表达式来破坏 html。你最终会扯掉你剩下的头发。使用DOM
  • 你为什么不直接使用 strip_tags(get_the_content(), '

    '); ?

  • get_the_content 不运行the_content 过滤器,其中一个添加了&lt;p&gt; 标签,所以是的,这是正常的。
  • @MarcB 好的,那是错误的。我是一个完全的 php 菜鸟。我一直在网上寻找解决方案,我发现了这种正则表达式方法。
  • @fabiantheblind:你在网上找到的很多 php“提示”都是废话(字面意思)或完全错误。那里有很多错误信息。在他们自己有限的情况下,它们可能为发布它们的人工作,但绝不应该用作一般解决方案。

标签: php regex wordpress preg-replace


【解决方案1】:

好的,我会回答我自己的问题:

  1. 是的,get_the_content() 上没有&lt;p&gt; 是正常的,谢谢@s_ha_dum
  2. 要添加&lt;p&gt;,我需要将内容过滤器应用为mentioned here(向下滚动到“替代用法”)。
  3. 正则表达式没有错,但正则表达式 html 很脏。谢谢@MarcB

查看导致以下代码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(']]>', ']]&gt;', $no_image_content);
echo $no_image_content;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-23
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多