我在数据库中存储文本。下面是正文:
".$teamName.", is the name of a recently formed company hoping to take over the lucrative hairdryer design ".$sector."
查询数据库后,我将此文本赋值给一个名为$news
的变量,然后回显它。
然而,文本输出到屏幕上完全如上所述,没有将变量$teamName*
和$sector
替换为相应的值。
我向您保证,$teamName
和$sector
都是在我查询数据库之前定义的。
我想做的事有可能做到吗?
您最好在这里使用sprintf()
。
$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.
在数据库中存储$string
。使用sprintf()
替换变量值
尝试使用这个,我猜:http://php.net/manual/en/function.sprintf.php
这是一个大胆的猜测,但是您是否将变量名称存储在数据库中,因为它们可能在单引号中并且没有求值?
$foo = 'bar';echo '$foo'; //$foo
$foo = 'bar';echo "$foo"; //bar
不是这样的。如果您希望计算$teamname
,则需要在将其存储到数据库之前对其进行计算。如果您需要它们变化,您可以对所有变量进行某种字符串替换。
SQL: INSERT INTO ... VALUES ( 'My team has won ##num_won## games this year.')
$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.
您应该在数据库中存储以下字符串(与您的略有不同):
$teamName, is the name of a recently formed company hoping to take over the lucrative hairdryer design $sector.
然后,你可以做两件事中的一件:
$news = eval('return "'.$news.'";');
…或…
$news = str_replace(array('$teamName','$sector'),array($teamName,$sector),$news);
或者更好,使用sprintf()
,其中字符串为:
%s, is the name of a recently formed company hoping to take over the lucrative hairdryer design %s.
…你得到的实际值是这样的:
$news = sprintf($news, $teamName, $sector);