0

so I have this email template that consist of something of a template strings

<p>My name is {name}</p>

that later on, when I trigger email function, I can just do file_get_contents and use str_replace to replace that part with the correct value

$temp = file_get_contents(__DIR__.'/template/advertise.html');
$temp = str_replace('{img}','mysite.com/assets/img/face.jpg',$temp);

Now what wanted this time is to get those word inside {} and append to an array $words = [];

What I've tried is using explode technique e.g.

$word = 'Hello {img}, age {age}, I live in {address}';

$word = explode('}',$word);

$words = [];

foreach( $word as $w ){
  $words[] = explode('{',$w)[1];
}

print_r($words);

but is there other better way to do this? any ideas, help?

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164

1 Answers1

0

Try the following:

$word = 'Hello {img}, age {age}, I live in {address}';

if (preg_match_all('/\{([^\}]+)\}/', $word, $matches, PREG_PATTERN_ORDER)) {
    var_dump($matches[1]);  
}

It should return all the variable names inside the curly braces.

Vlam
  • 1,622
  • 1
  • 8
  • 17