I have string like this in database (the actual string contains 100s of word and 10s of variable):
I am a {$club} fan
I echo this string like this:
$club = "Barcelona"; echo $data_base[0]['body'];
My output is I am a {$club} fan
. I want I am a Barcelona fan
. How can I do this?
The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.
Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.
Variable substitution is a way to embed data held in a variable directly into string literals. PHP parse double-quoted (and heredoc) strings and replace variable names with the variable's value. By BrainBell. May 12, 2022.
Use strtr
. It will translate parts of a string.
$club = "Barcelona"; echo strtr($data_base[0]['body'], array('{$club}' => $club));
For multiple values (demo):
$data_base[0]['body'] = 'I am a {$club} fan.'; // Tests $vars = array( '{$club}' => 'Barcelona', '{$tag}' => 'sometext', '{$anothertag}' => 'someothertext' ); echo strtr($data_base[0]['body'], $vars);
Program Output:
I am a Barcelona fan.
/** * A function to fill the template with variables, returns filled template. * * @param string $template A template with variables placeholders {$variable}. * @param array $variables A key => value store of variable names and values. * * @return string */ public function replaceVariablesInTemplate($template, array $variables){ return preg_replace_callback('#{(.*?)}#', function($match) use ($variables){ $match[1] = trim($match[1], '$'); return $variables[$match[1]]; }, ' ' . $template . ' '); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With