首页 > 解决方案 > 该函数只处理最后寻找的模式。怎么了?

问题描述

/**
 * Quick Links for ACF
 */
function replace_text($content) {
    $quick_links = get_field('quick_links', 'option');
    if($quick_links && is_singular('post')) {
        foreach($quick_links as $item) {
            $word = $item['word_quick_links'];
            $link = $item['link_quick_links'];
            $preg_replace = preg_replace('/\b'.preg_quote($word, '/').'\b/', '<a href="' . $link . '" target="_blank">' . $word . '</a>', $content, 1);
        }
        return $preg_replace;
    } else {
        return $content;
    }
}
add_filter('the_content', 'replace_text', 20 );

在 preg_replace() 函数中,最后一个参数是 limit - 每个主题行的每个模板的最大可能替换次数。默认情况下它等于-1(没有限制)。

我的错误是什么,为什么函数处理只有一个最后一个寻找的模板?

标签: phpwordpressadvanced-custom-fields

解决方案


在替换内容中文本的内部循环中,您总是从原始文本 ( $content) 开始并返回一个新字符串 ( $preg_replace)...

    $preg_replace = preg_replace('/\b'.preg_quote($word, '/').'\b/', '<a href="' . $link . '" target="_blank">' . $word . '</a>', $content, 1);

相反,您应该将结果放回原始内容中,以便下一个循环将添加到替换而不是获取新字符串(因此将新值放回$content)...

    $content = preg_replace('/\b'.preg_quote($word, '/').'\b/', 
        '<a href="' . $link . '" target="_blank">' . $word . '</a>',
        $content, 1);

然后返回这个值(你总是可以返回$content...

    return $content;

推荐阅读