PHP:当变量(b)包含文本时,如何在另一个变量(b)中显示变量(a)

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?

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.

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

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.

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);

Try this:

$teamName = 'foo';
$sector = 'bar';
$news = $teamname . ', is the name of a recently formed company hoping to take over the lucrative hairdryer design ' . $sector '.';
echo $news;

If you actually want the double quotations to be displayed, then try:

$news = '\"' . $teamname . '\", is the name of a recently formed company hoping to take over the lucrative hairdryer design \"' . $sector . '\".';