正则表达式提取2个花括号之间的字符串 [英] Regex extract string between 2 curly braces

查看:1383
本文介绍了正则表达式提取2个花括号之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下短代码:

亲爱的{{name}}

正在邀请您参加以下活动:{{event}}

You are being invited for the following event: {{event}}

致谢,{{author}}

我有一个来自数据库的数组: $data

I have an array from the database : $data

其中:

$data['name'] = 'John Doe';
$data['event'] = 'Party yay!';
$data['author'] = 'Kehke Lunga';

我期望的输出:

尊敬的John Doe,

Dear John Doe,

您受邀参加以下活动:派对!!

You are being invited for the following event: Party yay!

致谢Kehke Lunga

regards, Kehke Lunga

此外,我还想执行类似{{firstname||lastname}}的操作,该操作应检查是否已设置键$data['firstname'],如果未设置,则应使用$data['lastname'].但是,这是以后的事情.

also, I also want to perform operations like {{firstname||lastname}} which should either check if key $data['firstname'] is set, if it isn't it should use $data['lastname']. However, that is for later stage.

现在,我只想知道如何在2个花括号之间匹配文本.

For now, I just want to know how to match the text between 2 curly braces.

谢谢

推荐答案

对于第二个操作,您可能需要这样:

And for the second operations you need it could be something this way:

$str = "Dear {{name||email}}, You are being invited for the following event: {{event}}. Regards, {{author}}";

// $data['name'] = 'John Doe'; 
$data['email'] = 'JohnDoe@unknown.com'; 
$data['event'] = 'Party yay!'; 
$data['author'] = 'Kehke Lunga';

$pattern = '/{{(.*?)[\|\|.*?]?}}/';

$replace = preg_replace_callback($pattern, function($match) use ($data)
{
    $match = explode('||',$match[1]);

    return isset($data[$match[0]]) ? $data[$match[0]] : $data[$match[1]] ;
}, $str);

echo $replace;

基本上,通过编辑"$ pattern",然后在回调中找到所需的正确逻辑.

Basically by editing the '$pattern', and then find the correct logic needed inside the callback.

这篇关于正则表达式提取2个花括号之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆