-3

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.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
soonic
  • 595
  • 1
  • 7
  • 22

4 Answers4

5

Use str_replace instead of preg_replace:

$template = "My name is {NAME}. I'm {AGE} years old.";
$template = str_replace("{NAME}", "Tom", $template);
$template = str_replace("{AGE}", "10", $template);
Lakremon
  • 787
  • 1
  • 8
  • 26
1

Regex pattern should have delimiter at start and end of it

$template = "My name is {NAME}. I'm {AGE} years old.";
$template = preg_replace("/{NAME}/", "Tom", $template);
echo $template = preg_replace("/{AGE}/", "10", $template);
splash58
  • 26,043
  • 3
  • 22
  • 34
1

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

preg_replace is not the right function to use in this situation. In this case, the correct option would be str_replace or str_ireplace. However, for a large amount of data to format, using regex would be a better idea:

$associative_formatter_array = array('NAME' => 'Tom', "AGE" => '10');
$template = "My name is {NAME}. I'm {AGE} years old.";
$template = preg_replace_callback("`\{([^\}]*)\}`g", function($match) {
  return $_GLOBALS["associative_formatter_array"][$match[1]];
});
RamenChef
  • 5,557
  • 11
  • 31
  • 43