How to manually interpolate a string? [duplicate]

独自空忆成欢 提交于 2019-11-28 07:36:45

问题


This question already has an answer here:

  • How replace variable in string with value in php? 11 answers

The only way I've found to interpolate a string (I.E. expand the variables inside it) is the following:

$str = 'This is a $a';
$a = 'test';
echo eval('return "' . $str . '";');

Keep in mind that in a real-life scenario, the strings are created in different places, so I can't just replace 's with "s.

Is there a better way for expanding a single-quoted string without the use of eval()? I'm looking for something that PHP itself provides.

Please note: Using strtr() is just like using something like sprintf(). My question is different than the question linked to in the possible duplicate section of this question, since I am letting the string control how (I.E. through what function calls or property accessors) it wants to obtain the content.


回答1:


Here is a possible solution, not sure in your particular scenario if this would work for you, but it would definitely cut out the need for so many single and double quotes.

<?php
class a {
    function b() {
        return "World";
    }
}
$c = new a;
echo eval('Hello {$c->b()}.');
?>



回答2:


There are more mechanisms than PHP string literal syntax to replace placeholders in strings! A pretty common one is sprintf:

$str = 'This is a %s';
$a   = 'test';
echo sprintf($str, $a);

http://php.net/sprintf

There are a ton of other more or less specialised templating languages. Pick the one you like best.




回答3:


Have you heard of strtr() ? http://php.net/manual/en/function.strtr.php

it serves this very purpose and is very useful to create dynamic html containing infos from a database for exemple

given the following string:

$str = 'here is some text to greet user {zUserName}';

then you can parse it using strtr():

$userName = 'Mike';
$parsed = strtr($str,array('{zUserName}'=>$userName));
echo $parsed; // outputs: 'here is some text to greet user Mike'

While sprintf is faster on some regards, strtr allows you to control what goes where in a more friendly way (sprintf is not really manageable on very long strings containing say a hundred placeholders to be replaced)



来源:https://stackoverflow.com/questions/24912055/how-to-manually-interpolate-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!