2011-11-30 91 views
1

我正在將文本存儲在我的數據庫中。 這裏是下面的文字:PHP:當變量(b)包含文本時,如何在另一個變量(b)中顯示變量(a)

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

查詢我給你這個文本到一個名爲$news變量的數據庫,然後呼應它之後。

但是,文本完全按照上面的方式輸出到屏幕上,而不會將變量$teamName*$sector替換爲相應的值。

我向你保證在我查詢數據庫之前定義了$teamName$sector

它甚至有可能做我想做的事情嗎?

回答

4

在這裏,您最好使用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()替代變量值。

+1

的確。這比「eval」更安全,可能更快。 –

+0

謝謝,生病了試試 – NeverPhased

0

這是胡亂猜測,但你因爲也許他們在單引號和不評估存儲在數據庫中的變量名?

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

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

0

這不是它的工作原理。如果要對$teamname進行評估,則需要先將其評估,然後再將其存儲在數據庫中。如果你需要改變它們,你可以爲所有變量做一些字符串替換。

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. 
0

你應該存儲在數據庫中的以下字符串(略有不同,你的):

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

試試這個:

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

如果你真的想顯示的雙引號,然後嘗試:

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