2012-04-03 97 views
0

文本這將是數據的Array:PHP替換圖像

$array = array("sad","bow","blabla"); 

IF $input = "I love Stackoverflow! :bow: so much";

輸出應該是:

I love Stackoverflow <img src="smiley/bow.gif" alt=""/> so much 

什麼是最好和最快的方式完成這個?

+0

我是PHP新手,所以我不知道從哪裏開始...任何幫助讚賞 – enloz 2012-04-03 07:00:31

+1

http://php.net/str_replace? – mishu 2012-04-03 07:01:10

+0

或[preg_replace](http://php.net/manual/ru/function.preg-replace.php) – k102 2012-04-03 07:02:22

回答

1
$array = array(':('=>"sad",'-_-'=>"bow",'bla'=>"blabla"); 
$input = "I love Stackoverflow! :bow: so much"; 
$output = str_replace(array_keys($array), array_values($array), $input); 

編輯: Sorry..didn't讀清楚。

嘗試2:

preg_replace('`:(\w+):`', '<img src="smily/\1.gif" alt=""/>', $input); 

成才一樣,反正。可能必須使用$1代替\1。閱讀the docs

0
//string replace example. 
$input = "I love Stackoverflow! :bow: so much"; 
echo str_replace(":bow:","< img src='smiley/bow.gif' alt=''/>",$input)."<br /><br />"; 


//use string replace with foreach 
$array = array("sad","bow","blabla"); 

foreach($array as $value) 
{ 
    $input = "I love Stackoverflow! :'".$value."': so much"; 
    echo str_replace(":'".$value."':","< img src='smiley/$value.gif' alt=''/>",$input); 
}