Wordpress:循环内的preg_replace仅偶尔起作用

问题描述 投票:0回答:1

我正在尝试使用每个帖子的更改HTML内容制作一个自定义RSS feed

在模板文件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个将被完全替换。其余的将获得前两个替代品,而不是第三个。有人知道为什么吗?

php regex wordpress preg-replace
1个回答
0
投票

结果证明,该解决方案与循环或preg_replace无关。某些帖子的内容不包含任何HTML标记,仅包含纯文本。这就是preg_replace对它们没有任何影响的原因。但是,当这些内容在RSS feed中呈现时,将插入[[0 [自动])。这就是让我相信第三次替换被忽略的原因。

<p>
转向

First paragraph. Second paragraph.

© www.soinside.com 2019 - 2024. All rights reserved.