php - Preg_replace 与数组替换

标签 php regex string

$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 之类的东西在单次运行中完成吗?

最佳答案

您可以将 preg_replace_callback 与一个回调一起使用,一个接一个地消耗您的替换:

$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.

关于php - Preg_replace 与数组替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9416175/

相关文章:

javascript - Laravel5.5路由; 500内部服务器错误)

php - 从 PHP 一个简单的 Linux 脚本返回 "Hello World"

使用模式在雪花中替换 Regex_replace

.net - 字符串正则表达式的结尾是否在 .NET 中进行了优化?

javascript - 如果将正则表达式传递给 "RegExp"构造函数会发生什么?

php - 为什么 PHP 中两个字符串相加 "+"会产生这个结果?

php - codeigniter 表单回调值

python - 如何在 Python 2.7 中编写正则表达式以返回字符串中的两个单词,并在它们之间使用下划线

c++ - 将文件内容读入动态分配的 char* 数组——我可以改为读入 std::string 吗?

php - 一个类可以扩展一个类并实现一个接口(interface)吗