PHP 根据字符串中的位置替换动态内容

PHP replace dynamic content based on position in string

我想要什么:

要替换的值介于 {{ }}.

之间

输入: "this is letter {{ A }} and {{ B }}"

但它可以改变:"this is letter {{ AAAA }} and {{ BBB }}"

with array ("C", "D")

输出: "this is letter C and D


我事先不知道 {{ }} 之间的字符串,我想提取这些字符串并用另一个值替换它们:

我试过的:

$body = "This is a body of {{awesome}} text {{blabla}} from a book.";


//Only work if we know the keys (awesome, blabla,...)
$text["awesome"] = "really cool"; 
$text["blabla"] = "";
echo str_replace(array_map(function($v){return '{{'.$v.'}}';},    array_keys($text)), $text, $body);

结果:

This is a body of really cool text from a book.

问题:

我找不到与这个已经问过的类似的东西(只有当我们知道括号之间的旧内容之前,但我的是 "dynamic"),所以 [=60 的解决方案=]preg_replace_callback 不起作用。

知道我该怎么做吗?

$body = "This question is a {{x}} of {{y}} within SO.";

$text = ['possible duplicate', '@21100035'];

echo preg_replace_callback('~{{[^{}]++}}~', function($m) use ($text, &$count) {
    return $text[(int)$count++] ?? $m[0];
}, $body, -1, $count);

// Output
// This question is a possible duplicate of @21100035 from SO.

Live demo

<?php

$body = "This question is a {{x}} of {{y}} within SO.";

$searches = ['{{x}}', '{{y}}'];
$replaces = ['possible duplicate', '@21100035'];

echo str_replace($searches, $replaces, $body);

// Output
// This question is a possible duplicate of @21100035 from SO.

编辑: 如果你不知道 X & Y 那么你可以试试这个

<?php

$body = "This question is a {{x}} of {{y}} within SO.";

preg_match_all('/\{\{(.*?)\}\}/', $body, $matches);

$searches = $matches[0];
$replaces = ['possible duplicate', '@21100035'];

echo str_replace($searches, $replaces, $body);

// Output
// This question is a possible duplicate of @21100035 from SO.

我想这就是你想要的:

$body = "This is a body of {{awesome}} text {{blabla}} from a book.";
$count = 0;
$terms[] = '1';
$terms[] = '2';
echo preg_replace_callback('/\{{2}(.*?)\}{2}/',function($match) use (&$count, $terms) {
    $return = !empty($terms[$count]) ? $terms[$count] : 'Default value for unknown position';
    $count++;
    return $return;
}, $body);

演示:https://3v4l.org/Ktaod

这将找到每个 {{}} 对,并根据它在字符串中找到的位置用数组中的值替换该值。

正则表达式 \{{2}(.*?)\}{2} 只是在寻找 2 {s,介于两者之间的任何东西,然后是 2 }s.