4

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

kamal pal
  • 4,187
  • 5
  • 25
  • 40
karmicdice
  • 1,063
  • 9
  • 38

5 Answers5

4

With preg_match_all():

$pattern = '~\{\{(.*?)\}\}~';
preg_match_all($pattern, $string, $matches);
var_dump($matches[1]);
kamal pal
  • 4,187
  • 5
  • 25
  • 40
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
3

Use 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);

output:

Dear John Doe,
    You are being invited for the following event: Party yay!
    regards, Kehke Lunga
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 2
    Looks like this fits more the OP's needs. I have to admit that I just read the headline of the question :) ... – hek2mgl Dec 14 '13 at 11:04
3

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;

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

ilpaijin
  • 3,645
  • 2
  • 23
  • 26
2

Use preg_match to match the text between 2 curly braces :

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

Take a look at similar Question

Community
  • 1
  • 1
Denis
  • 121
  • 4
1
$matches = array();
$a="{{name}}";
preg_match('/\{(.+)\{(.+)\}\}/', $a, $matches);

var_dump($matches);
saloni
  • 121
  • 4