soonic soonic - 4 months ago 26
PHP Question

preg_replace and big brackets {}

I want to make an email template and how to replace everything in the brackets

{}
and with the brackets
{}
?

$template = "My name is {NAME}. I'm {AGE} years old.";
$template = preg_replace("{NAME}", "Tom", $template);
$template = preg_replace("{AGE}", "10", $template);


and after that should look like this:
My name is Tom. I'm 10 years old.

Answer

You can use preg_replace() with single line like below (better than str_replace()):-

$template = "My name is {NAME}. I'm {AGE} years old.";
$find = array('/{NAME}/', '/{AGE}/');
$replace = array('TOM', '10');
$template = preg_replace($find, $replace, $template);

echo $template;

Output:- https://eval.in/606528

Note:- it have below benefits:-

1. Single line code to replace all you want. not needed again and again str_replace().

2. If some more replacement needed in future then you have to add them into $find and $replace and that's it. So it is more flexible.

Sorry i totally forgot to mention that str_replace() will also works with array so you can do it like below too:-

<?php

$template = "My name is {NAME}. I'm {AGE} years old.";
$find = array('{NAME}', '{AGE}');
$replace = array('TOM', '10');
$template = str_replace($find, $replace, $template);

echo $template;

Output:-https://eval.in/606577

Note:- Both are equally good. You can go for any one. Thanks