$name = "MasterOfDisaster";
$age = "666";
$string = "My name is [name] and i'm [age] years old";
Now I' would like to replace all values between two characters and change them to a same named php variable
[foo] > $foo
I want to get this without replacing with arrays:
$string = "My name is $name and i'm $age years old";
Can I achieve this with ereg_replace? I'don't want to use str_replace() in combination with arrays to catch all my values in the text.
My preg_replace() so far:
$placeholder = preg_replace("/\[(.*?)]/", ${"$1"}, $string);
echo $placeholder;
You can use like this:
$array = array('name' => "MasterOfDisaster", 'age' => "666");
$string = "My name is [name] and i'm [age] years old";
foreach ($array as $key => $value) {
$string = preg_replace('/\['.$key.'\]/i', $value, $string);
}
echo $string;
Output is:
My name is MasterOfDisaster and i'm 666 years old
NOTE: Do not use ereg_replace
functions because it is deprecated. Yous preg_replace
functions instead.