Preg_replace与阵列替换 [英] Preg_replace with array replacements

查看:141
本文介绍了Preg_replace与阵列替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');

应成为:

Mary and Jane have apples.

现在我正在这样做:

preg_match_all('/:(\w+)/', $string, $matches);

foreach($matches[0] as $index => $match)
   $string = str_replace($match, $replacements[$index], $string);

我可以使用preg_replace之类的工具一次完成此操作吗?

Can I do this in a single run, using something like preg_replace?

推荐答案

您可以将preg_replace_callback与回调一起使用,该回调消耗您的替换项:

You could use preg_replace_callback with a callback that consumes your replacements one after the other:

$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');
echo preg_replace_callback('/:\w+/', function($matches) use (&$replacements) {
    return array_shift($replacements);
}, $string);

输出:

Mary and Jane have apples.

这篇关于Preg_replace与阵列替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆