2012-04-23 103 views
0

替換文本我有這樣的功能:PHP - 用笑臉

function bb_parse($string) { 
     $string = $this->quote($string); 
      $string=nl2br($string); 
     $string = html_entity_decode(stripslashes(stripslashes($string))); 
      $tags = 'b|i|u'; 
      while (preg_match_all('`\[('.$tags.')=?(.*?)\](.+?)\[/\1\]`', $string, $matches)) foreach ($matches[0] as $key => $match) { 
       list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]); 
       switch ($tag) { 
        case 'b': $replacement = "<strong>$innertext</strong>"; break; 
        case 'i': $replacement = "<em>$innertext</em>"; break; 
        case 'u': $replacement = "<u>$innertext</u>"; break; 
          } 
       $string = str_replace($match, $replacement, $string); 
      } 

      return $string; 
     } 

正如你所看到的,我可以很容易地使用的BBCode粗體,斜體和下劃線。雖然,我正在嘗試爲此功能添加表情符號,但沒有運氣。

我試圖只是簡單地添加:)到$標記,然後添加笑臉:)在這種情況下,但沒有工作。

我該怎麼做,所以我也可以添加表情符號呢?

在此先感謝。

+1

您可能希望使用單獨的'str_replace'調用來執行表情符號,因爲它們不需要配對標記的正則表達式解析。 – Amber 2012-04-23 07:02:57

+0

':)'不是標籤。這就是爲什麼你的正則表達式失敗。 – Jack 2012-04-23 07:07:49

+0

類似的問題,其答案包括一些你可能想要考慮的其他事情:[匹配和替換字符串中的表情符號 - 什麼是最有效的方式?](http://stackoverflow.com/q/9295896/1191425)。 (tchrist的回答是高級的樂趣) – 2012-04-23 07:22:16

回答

1

只需創建,做了簡單的str_replace的功能,我會說:

<?php 

function smilies($text) { 
    $smilies = array(
     ';)' => '<img src="wink.png" />', 
     ':)' => '<img src="smile.png" />' 
    ); 

    return str_replace(array_keys($smilies), array_values($smilies), $text); 
} 

$string = '[b]hello[/b] smile: :)'; 

echo smilies(bb_parse($string)); 
+0

如果我有笑臉':/'就像'http://裏面'它也會被替換嗎?因爲它不應該。 – Luka 2017-02-23 11:23:04