【发布时间】:2022-01-06 19:22:12
【问题描述】:
我正在尝试用 2 个属性或有时只有 1 个属性替换模板中的多个变量。
目前,如果没有第二个属性,则最后一个字符被第二个正则表达式组捕获。
$content = 'Lorem ipsum {monthly_price} and {yearly_price|site-network} Lorem ipsum';
function get_replacement($matches) {
$attr = $matches[1]; // Index 1 is the first capture group
$deal = $matches[2];
return $attr;
}
$content = preg_replace_callback('/{([a-z_]+)\|?([a-z-]+)}/', 'get_replacement', $content);
echo $content;
输出:
Lorem ipsum monthly_pric and yearly_price Lorem ipsum
【问题讨论】:
-
将您的正则表达式更改为
/{([a-z_]+)(?:\|([a-z-]+))?}/。否则,您寻求的结果不清楚。