我有一个字符串,其中包含大括号中的变量,我想用一个值替换它们。
$text = 'Hi My Name is ##{Name}## and I am ##{Adjective}##';
preg_match_all('/{([^#]+)}/i', $text, $matches);
foreach ($matches[1] as $key => $value) {
$text = str_replace('{' . $value . '}', 'SomeValue', $text);
}
print_r($matches[1]);
print_r(str_replace('##', '', $text));
输出
Array ( [0] => Name [1] => Adjective )
Hi My Name is SomeValue and I am SomeValue
但是我无法处理字符串的不同变体。
1. $text = 'Hi My Name is ##{Name}{Adjective}##'
2. $text = 'Hi My Name is ##{Name}and I am{Adjective}##'
3. $text = 'Hi My Name is ##{Name}, {Adjective}##'
4. $text = 'Hi My Name is ##{Name} {Adjective}##'
我希望在数组输出中得到类似的结果,以便可以替换值
Array ( [0] => Name [1] => Adjective )
注意:我能够确保“##”始终出现在大括号的开头和结尾,但不一定出现在大括号之间,例如示例字符串中的点 1,2,3,4。
最佳答案
我建议使用preg_replace_callback
使用模式 /\{(.+?)}/
和这样的回调
$callback = function($matches) use (&$found) {
$found[] = $matches[1];
return 'SomeValue';
};
这将允许您在 $found
数组中记录匹配项,同时将整个 {Name}
、{Adjective}
替换为“SomeValue ”。
$found = [];
$newTxt = str_replace('##', '',
preg_replace_callback('/\{(.+?)}/', $callback, $txt));
此处演示 ~ https://eval.in/641827
关于php - 正则表达式未按预期工作 - PHP preg_match_all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39482597/