【问题标题】:PHP - replace text with smileyPHP - 用笑脸替换文本
【发布时间】:2012-05-03 19:13:56
【问题描述】:

我有这个功能:

  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。虽然,我也在尝试为这个功能添加笑脸,但没有运气。

我尝试简单地将 :) 添加到 $tags,然后在案例中添加笑脸 :) img,但这不起作用。

我该怎么做,这样我也可以添加表情符号?

提前致谢。

【问题讨论】:

  • 您可能希望通过单独的str_replace 调用来制作表情符号,因为它们不需要正则表达式解析配对标签。
  • :) 不是标签。这就是你的正则表达式失败的原因。
  • 类似问题,其答案包括您可能需要考虑的其他一些问题:Match and replace emoticons in string - what is the most efficient way?。 (tchrist 的回答很有趣。)

标签: php regex replace bbcode


【解决方案1】:

http://php.net/manual/en/function.preg-quote.php

你必须逃避你的笑脸标签。

 $tags = 'b|i|u|'.preg_quote(":)");

【讨论】:

    【解决方案2】:

    只需创建一个执行简单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 ) );
    

    【讨论】:

    • 如果我有笑脸:/,就像在http://里面一样,它也会被替换吗?因为它不应该。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多