【问题标题】:PHP template multiple variable replace with seperatorPHP模板多个变量用分隔符替换
【发布时间】: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-]+))?}/。否则,您寻求的结果不清楚。

标签: php regex


【解决方案1】:

$deal = $matches[2]; 是浪费的代码行,因为您没有对分配的变量做任何事情。

要修复您的模式并使以管道开头的部分为可选,您需要创建一个可选的非捕获组。

代码:(Demo)

$content = 'Lorem ipsum {monthly_price} and {yearly_price|site-network} Lorem ipsum'; 
function get_replacement($matches) {
    var_export($matches);
    echo "\n---\n";
    return "<< {$matches[1]}" . (isset($matches[2]) ? " & {$matches[2]}" : '') . " >>";
}
echo preg_replace_callback('/{([a-z_]+)(?:\|?([a-z-]+))?}/', 'get_replacement', $content);

输出:

array (
  0 => '{monthly_price}',
  1 => 'monthly_price',
)
---
array (
  0 => '{yearly_price|site-network}',
  1 => 'yearly_price',
  2 => 'site-network',
)
---
Lorem ipsum << monthly_price >> and << yearly_price & site-network >> Lorem ipsum

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    相关资源
    最近更新 更多