I Want change all Strings starting with {" and ending with "}
to a variable, for example:
Hello {username}, -> to Hello $array['username']
Your Country is {country}, -> Your Country is $array['country']
But i get all strings text from database with one variable (Mysql) With $array['content']
What I Want:
str_replace("{$whatinhere}",$array['$copytohere'],$array['content']);
str_replace("{company}",$array['company'],$array['content']);
Use preg_replace_callback function
echo preg_replace_callback('~{(.+?)}~',
function($x) use ($array) { return isset($array[$x[1]]) ? $array[$x[1]] : ''; },
$array['content']);
I think you should try this...
$content = $array['content'];
$mainContent = str_replace('{username}', $array['username'], $content);
$mainContent = str_replace('{company}', $array['company'], $mainContent);
echo $mainContent;
As I understand the $array
variable contains the placeholder key/value pairs and also the content. You can try following code for replacing all placeholder keys with their corresponding values:
foreach ($array as $key => $value) {
if ($key != "content") {
$array["content"] = str_replace("{" . $key . "}", $value, $array["content"]);
}
}
/** Print contents */
echo $array["content"];
This is my full code.
$sql = mysqli_query($db, "SELECT * FROM templates WHERE id = '$id' LIMIT 1");
$array = mysqli_fetch_array($sql);
echo str_replace({username}",$arraybf['username'],$array['content']);
echo str_replace({company}",$arraybf['company'],$array['content']);