首页 > 解决方案 > Wordpress:循环内的 preg_replace 仅偶尔有效

问题描述

我正在尝试制作一个自定义 RSS 提要,并对每个帖子的 HTML 内容进行一些更改。

在模板文件中rss-custom.php我有这个:

<?php while (have_posts()) : the_post(); ?>
  <?php echo processPostContent(); ?>
<?php endwhile; ?>

functions.php,有以下三个替换:

function processPostContent() {
    $post = get_post(get_the_ID());
    $post_content = strval($post->post_content);
    // replace h3 and h4 tags with h2
    $post_content = preg_replace('/<(\/?)h((?![12])\d)/im', "<$1h2", $post_content);
    // strip every attribute of <img> other than src
    $post_content = preg_replace('/<img[^>]*(src="[^"]*")[^>]*>/im', "<img $1 />", $post_content);
    // insert text after some closing tags
    $post_content = preg_replace('/<\/(h2|p|figure)>/im', "</$1><p>Inserted</p>", $post_content);

    return $post_content;
}

然后我得到一个奇怪的结果:在 20 个帖子中,只有 7-8 个会被完全替换。其余的得到前两个替换,但不是第三个。有谁知道这是为什么?

标签: phpregexwordpresspreg-replace

解决方案


事实证明,该解决方案与循环或preg_replace. 有些帖子的内容不包含任何 HTML 标签,只有纯文本。这就是为什么preg_replace对他们没有任何影响。但是,当这些内容在 RSS 提要中呈现时,会自动插入<p>标签。这就是让我相信第三次替换被跳过的原因。

First paragraph.
Second paragraph.

转向

<p>First paragraph.</p>
<p>Second paragraph.</p>

推荐阅读