You can use preg_match_all to match all the keywords wrapped by square brackets:
$text = 'Dear [NAME],
<br /><br />
Someone (hopefully you) requested a password reset at [SITE_URL].
<br /><br />
To reset your password, please follow the following link: [EMAIL_LINK]';
preg_match_all('/\[([A-Z_]+)\]/', $text, $matches);
By var_dump
ing the $matches
variable you will get:
array(2) {
[0]=>
array(3) {
[0]=>
string(6) "[NAME]"
[1]=>
string(10) "[SITE_URL]"
[2]=>
string(12) "[EMAIL_LINK]"
}
[1]=>
array(3) {
[0]=>
string(4) "NAME"
[1]=>
string(8) "SITE_URL"
[2]=>
string(10) "EMAIL_LINK"
}
}
So, let's suppose you will have an array of keywords to be replaced:
$keywords = array(
'NAME' => 'Mihai MATEI',
'SITE_URL' => 'http://example.com/',
'EMAIL_LINK' => '<a href="mailto:contact@example.com">contact@example.com</a>',
);
You can replace the keywords in the template as:
foreach ($matches[1] as $key => $keyword) {
$text = str_replace($matches[0][$key], $keywords[$keyword], $text);
}
Now if you var_dump
the $text
variable will get:
Dear Mihai MATEI,
<br /><br />
Someone (hopefully you) requested a password reset at http://example.com/.
<br /><br />
To reset your password, please follow the following link: <a href="mailto:contact@example.com">contact@example.com</a>