2012-04-23 134 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