Change part of text from mysql into variable name using php

问题: 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;
}
  • 发表于 2018-07-05 16:39
  • 阅读 ( 266 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除