回显一个带有变量的字符串,从DB中获取

I get from a MySQL query a string and I've to print it to screen. Into this string, I need to print some variable too. The string from DB could be:

Finally, the team {$matchData['team_name']} have scored a point!

$matchData['team_name'] is an array used during the calculation of the match, and if I do a simple

echo $matchData['team_name'];

will print the correct name of the team (BOSTON in this case). But why if I echo the string getted from DB, echo print:

Finally, the team {$matchData['team_name']} have scored a point!

and not

Finally, the team BOSTON have scored a point!

Where I fail?

PHP seems to handle variable substitution in strings only in the simpler cases... the foolproof way to make sure it always works is to use concatenation, like:

echo "Finally, the team ".$matchData['team_name']." have scored a point!";

The PHP man page does give this example though:

// You can also use arrays
$baz = array("value" => "foo");

echo "this is {$baz['value']} !"; // this is foo !

So you might want to double check your syntax against that, too.

Finally, echo takes a parameter list of variable length so you can also write:

echo "Finally, the team ", $matchData['team_name'], " have scored a point!";

Variable substitution in strings works in only exactly one case: in string literals in source code:

$foo = 'bar';
$baz = "This $foo works";

It does not work on any random input you get from anywhere else. Imagine what would happen if a user typed this into your webpage:

Hi, this is my $password.

If PHP would simply substitute $password for the variable of the same name, it'd be trivial to snoop out a program's internals. That's not the way it works.

The best thing for you to do is to explicitly leave placeholders in your database data and explicitly substitute them with explicitly defined data. E.g.:

$string = 'Finally, the team %s have scored a point!';
$team   = 'Foos';

printf($string, $team);

http://php.net/sprintf