替换字符串中看起来相同的多个单词

replace multiple words that look the same in a string

我在 PHP 中遇到了一点问题。

$string = "[:string] has [:int] [:string] and [:int] [:string]";

我只想修改(可能用 str_replace)它:

$string = "He has 5 apples and 3 bananas";

我该怎么做?

(经典的 str_replace() 将修改所有具有相同单词的 [:int],
这不是我想要的)。

非常感谢...

您可以使用以下正则表达式来捕获所有要替换的组,然后对其进行迭代。

\[:([^\]]+)\]

或者您可以只使用 preg_replace_callback 并将所需的替换函数传递给它。

$data = [...];
preg_replace_callback('/\[:([^\]]+)\]/', $str, function (&$matches) use ($data) {
    return doSomethingWithMatches..
});