php - 该函数只处理最后寻找的模式。怎么了?
问题描述
/**
* 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(没有限制)。
我的错误是什么,为什么函数处理只有一个最后一个寻找的模板?
解决方案
在替换内容中文本的内部循环中,您总是从原始文本 ( $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;
推荐阅读
- python - 当我使用串联数据框时,为什么会出现“IndexError:字符串索引超出范围”
- excel - 根据常用单元格值创建范围并创建匹配的范围名称
- javascript - Odoo AJAX 附件或图像创建到客户端(前端)
- javascript - 是否可以删除 Outlook 加载项中的漫游数据?
- python - 在 Pandas 中找到时间增量的模数
- javascript - 比较两个数组并连接它
- or-tools - 为什么使用 AUTOMATIC 优先解决方案策略解决这个 VRP 问题需要这么长时间?
- php - 如何在 Laravel 的工作中传递相同的连接实例?
- authentication - 不断提示用户进行生物识别访问
- payment-gateway - 如何使用 Authorize.Net 托管付款表单进行 AUTH_ONLY