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