How to replace placeholders with actual values?

后端 未结 6 930
逝去的感伤
逝去的感伤 2021-01-07 12:00

I need a function that replace every variable_name inside \'{}\' with the correct variable. Something like this:

$data[\"name\"] = \"Johnny\";
$data[\"age\"         


        
6条回答
  •  生来不讨喜
    2021-01-07 12:43

    I've always been a fan of strtr.

    $ php -r 'echo strtr("Hi @name. The weather is @weather.", ["@name" => "Nick", "@weather" => "Sunny"]);'
    Hi Nick. The weather is Sunny.
    

    The other advantage to this is you can define different placeholder prefix types. This is how Drupal does it; @ indicates a string to be escaped as safe to output to a web page (to avoid injection attacks). The format_string command loops over your parameters (such as @name and @weather) and if the first character is an @, then it uses check_plain on the value.

    Also answered here: https://stackoverflow.com/a/36781566/224707

提交回复
热议问题