问题:
Totally lost on how to solve. I have a mysql text record which contains the following text:
Hello $someone
When I output it in php, it shows as Hello $someone - which...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
Totally lost on how to solve. I have a mysql text record which contains the following text:
Hello $someone
When I output it in php, it shows as Hello $someone
- which is fine and what I expect.
However, how can I output it in php so that it turns $someone
into a php variable, which is assigned in php?... So I'd like my php code like:
$someone = "John Doe";
echo $subject;
returns: Hello John Doe
I've tried looking at variable variables, using $$someone
, ${$someone}
but always just returns text.
I understand that $someone
would always be a text, so would have to have it stored in mysql as something like {$someone}
to differentiate it from a dollar amount like $50 etc.
Any help would be greatly appreciated!
回答1:
Here's an exampe of a simple function that will replace placeholder values in a string. Both the strings ($text) and the data could easily come from the database.
$text = "";
$text .= "<p>Dear {name},</p>n";
$text .= "<p>Thank you for your order on {order_date}.</p>n";
$text .= "<p>You order was shipped on {ship_date}.</p>n";
$data = array(
"name" => "John Doe",
"order_date" => "05/01/2018",
"ship_date" => "05/04/2018",
"order_total" => "$22.50"
);
$textToDisplay = curly_replacer($text,$data);
echo $textToDisplay;
// Function to replace placeholders with data values.
// $str contains placeholder names enclosed in { }
// $data is an associative array whose keys are placeholder,
// and values are the values to replace the placeholders
function curly_replacer($str,$data) {
$rslt = $str;
foreach($data as $key => $val) {
$rslt = str_replace("{".$key."}", $val, $rslt);
}
return $rslt;
}