Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex extract string between 2 curly braces

Tags:

regex

php

I have the following short codes:

Dear {{name}},

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

regards, {{author}}

I have an array from the database : $data

where:

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

Output that I expect:

Dear John Doe,

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

regards, Kehke Lunga

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.

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

Thanks

like image 882
karmicdice Avatar asked Dec 12 '22 09:12

karmicdice


2 Answers

With preg_match_all():

$pattern = '~\{\{(.*?)\}\}~';
preg_match_all($pattern, $string, $matches);
var_dump($matches[1]);
like image 170
hek2mgl Avatar answered Dec 24 '22 06:12

hek2mgl


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'] = '[email protected]'; 
$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;

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

like image 23
ilpaijin Avatar answered Dec 24 '22 05:12

ilpaijin