PHP: How to display a variable (a) within another variable(b) when variable (b) contains text

梦想的初衷 提交于 2020-01-05 08:10:30

问题


I am storing text in my database. Here is the following text:

".$teamName.", is the name of a recently formed company hoping to take over the lucrative hairdryer design ".$sector."

After querying the database I assign this text to a variable called $news, then echo it.

However the text is outputted to the screen exactly as above without the variables $teamName*and $sector replaced by there corresponding values.

I assure you that both $teamName and $sector are defined before I query the database.

Is it even possible to do what I am trying to do?


回答1:


You might be better off using sprintf() here.

$string = "%s is the name of a recently formed company hoping to take over the lucrative hairdryer design %s.";

$teamName = "My Company";
$sector = "sector";

echo sprintf($string, $teamName, $sector);
// My Company is the name of a recently formed company hoping to take over the lucrative hairdryer design sector.

In your database, you store $string. Use sprintf() to substitute the variable values.




回答2:


Try using this, I guess: http://php.net/manual/en/function.sprintf.php




回答3:


This is a wild guess, but did you store the variable names in the database because maybe they were in single quotes and not evaluated?

$foo = 'bar';echo '$foo'; //$foo

$foo = 'bar';echo "$foo"; //bar




回答4:


That's not how it works. If you want $teamname to be evaluated, you need to evaluate it before you store it in the database. If you need them to vary, you could do some sort of string replace for all variables.

SQL: INSERT INTO ... VALUES ( 'My team has won ##num_won## games this year.')

PHP:

$string = get_string_from_sql(); // substitute for whatever method you are using to get the string.
$num_won = 16;
$string = str_replace('##num_won##', $num_won, $string);
echo $string; // Will echo My team has won 16 games this year.



回答5:


You should be storing the following string in your database (slightly different to yours):

$teamName, is the name of a recently formed company hoping to take over the lucrative hairdryer design $sector.

Then, you can do one of two things:

$news = eval('return "'.$news.'";');

...or...

$news = str_replace(array('$teamName','$sector'),array($teamName,$sector),$news);

Or better yet, use sprintf(), where the string is:

%s, is the name of a recently formed company hoping to take over the lucrative hairdryer design %s.

...and you get the actual value like this:

$news = sprintf($news, $teamName, $sector);


来源:https://stackoverflow.com/questions/8329454/php-how-to-display-a-variable-a-within-another-variableb-when-variable-b

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