0

I have this function:

  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;
        }

As you can see, I can easily make BBCode with bold, italic and underline. Although, I am trying to add smileys to this function as well, but without luck.

I tried to simply just add :) to the $tags, and then add the smiley :) img in the case, but that did not work.

How can I do, so I can also add smilies to this?

Thanks in advance.

Jack
  • 5,680
  • 10
  • 49
  • 74
oliverbj
  • 5,771
  • 27
  • 83
  • 178
  • 1
    You probably want to do smilies with a separate `str_replace` call, given that they don't need the regex parsing for paired tags. – Amber Apr 23 '12 at 07:02
  • `:)` isn't a tag. That's why your regex is failing. – Jack Apr 23 '12 at 07:07
  • Similar question, whose answers include some other things you may want to consider: [Match and replace emoticons in string - what is the most efficient way?](http://stackoverflow.com/q/9295896/1191425). (tchrist's answer is advanced fun.) – Li-aung Yip Apr 23 '12 at 07:22

2 Answers2

1

Just create a function that does a simple str_replace, I'd say:

<?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 ) );
Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
  • If I have smiley `:/` like inside `http://` will it also be replaced? Because it shouldn't. – Luka Feb 23 '17 at 11:23
0

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

You have to escape your smiley tags.

 $tags = 'b|i|u|'.preg_quote(":)");
K1773R
  • 922
  • 4
  • 10