正则表达式提取2个花括号之间的字符串

时间:2013-12-14 10:47:26

标签: php regex

我有以下短代码:

  

亲爱的{{name}}

     

您受邀参加以下活动:{{event}}

     

问候,{{author}}

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

其中:

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

我期望的输出:

  

亲爱的John Doe,

     

您被邀请参加以下活动:派对耶!

     

问候,Kehke Lunga

另外,我还想执行像{{firstname||lastname}}这样的操作,应检查是否设置了密钥$data['firstname'],如果不是,则应使用$data['lastname']。但是,这是为了后期阶段。

目前,我只想知道如何匹配两个大括号之间的文本。

由于

5 个答案:

答案 0 :(得分:4)

使用preg_match_all()

$pattern = '~\{\{(.*?)\}\}~';
preg_match_all($pattern, $string, $matches);
var_dump($matches[1]);

答案 1 :(得分:3)

使用preg_replace_callback

$data = array(
    'name' => 'John Doe',
    'event' => 'Party yay!',
    'author' => 'Kehke Lunga',
);

$str = 'Dear {{name}},
You are being invited for the following event: {{event}}
regards, {{author}}';

$str = preg_replace_callback('/{{(\w+)}}/', function($match) use($data) {
    return $data[$match[1]];
}, $str );

echo($str);

输出:

Dear John Doe,
    You are being invited for the following event: Party yay!
    regards, Kehke Lunga

答案 2 :(得分:3)

对于你需要的第二次操作,它可能是这样的:

$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',然后在回调中找到所需的正确逻辑。

答案 3 :(得分:2)

使用preg_match匹配2个大括号之间的文本:

$subject = "{{Lorem}}";
$pattern = '/\{\{([^}]+)\}\}/';
preg_match($pattern, $subject, $matches);
var_dump($matches);

查看类似的Question

答案 4 :(得分:1)

$matches = array();
$a="{{name}}";
preg_match('/\{(.+)\{(.+)\}\}/', $a, $matches);

var_dump($matches);