2014-01-20 13 views
0

我正在网站上制作这样的过程中,会有微笑,而写一些可以定义页面上的字符。这就是如何我试着这样做:展示内容中的笑容 - 没有微笑出现

   echo $tekst; 

       $smiles = array(
        ':)' => 'devil.png', 
        '>:)' => 'devil.png', 
        'x(' => 'angry.png', 
        ';-)' => 'wink.png' 
       ); 
       foreach($smiles as $key => $img) { 
        $msg = str_replace($key, "<img src=\"emotions/'.$img.'\" height=\"18\" width=\"18\" />", $msg); 
       } 
       echo $msg; 

正是这样会有什么网页上出现的。

问题是这样的,它不会显示微笑的图像。

+0

是在当前目录中的图片? –

回答

0

我想这是正确的代码:

$msg = 'Hello world :)!'; 

$smiles = array(
    ':)' => 'devil.png', 
    '>:)' => 'devil.png', 
    'x(' => 'angry.png', 
    ';-)' => 'wink.png' 
); 

foreach($smiles as $key => $img) { 
    $msg = str_replace($key, '<img src="emotions/'.$img.'" height="18" width="18" />', $msg); 
} 

echo $msg; 

尽量避免在PHP双引号字符串,他们往往是混乱和难以维护。

事实上,这样做部分的更好的方式是:

foreach($smiles as $key => $img) { 
    $img = sprintf('<img src="emotions/%s" height="18" width="18" />', $img); 
    $msg = str_replace($key, $img, $msg); 
} 
+0

现在的工作! :)感谢您的帮助! – Jesperbook

0

它看起来像你有一些额外的单引号。当你的代码目前,输出为:

Input: Hello :) world 
Hello <img src="emotions/'.devil.png.'" height="18" width="18" /> world 

如果改变这一行:

$msg = str_replace($key, "<img src=\"emotions/$img\" height=\"18\" width=\"18\" />", $msg); 

你得到正确的输出:

Hello <img src="emotions/devil.png" height="18" width="18" /> world 

这工作,因为PHP执行变量代换在字符串上使用双引号时。有关更多信息,请参阅this page in the PHP documentation

0

下需要改变

$msg = str_replace($key, "<img src=\"emotions/'.$img.'\" height=\"18\" width=\"18\" />", $msg); 
               ^^ ^^ 

产生<img src="emotions/'.devil.png.'" height="18" width="18" />

要:

$msg = str_replace($key, "<img src=\"emotions/$img\" height=\"18\" width=\"18\" />", $msg); 

产生<img src="emotions/devil.png" height="18" width="18" />

您应经常检查你的view-source来看看什么东西被生产或做var_dump