首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wordpress:循环中的preg_replace只偶尔工作

Wordpress:循环中的preg_replace只偶尔工作
EN

Stack Overflow用户
提问于 2019-12-05 09:10:42
回答 1查看 65关注 0票数 0

我试图制作一个自定义RSS ,并对每个帖子的HTMLContent做一些修改。

在模板文件rss-custom.php中,我有以下内容:

代码语言:javascript
复制
<?php while (have_posts()) : the_post(); ?>
  <?php echo processPostContent(); ?>
<?php endwhile; ?>

functions.php中,三种替代品如下:

代码语言:javascript
复制
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个将被完全取代。剩下的人得到前两个替代者,而不是第三个。有人知道为什么吗?

EN

回答 1

Stack Overflow用户

发布于 2019-12-05 10:36:48

结果,这个解决方案与循环和preg_replace没有任何关系。有些帖子的内容不包括任何HTML标签,只包含纯文本。这就是为什么preg_replace对他们没有任何影响的原因。但是,当这些内容在RSS中呈现时,<p>标记将自动插入。所以我才相信第三个替补被跳过了。

代码语言:javascript
复制
First paragraph.
Second paragraph.

转到

代码语言:javascript
复制
<p>First paragraph.</p>
<p>Second paragraph.</p>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59191669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档