Page 1 of 1

Bit of regex advice - smilies

Posted: Thu Sep 08, 2005 8:51 pm
by evilmonkey
Hello,

I'm writing a system that will recognize smilies in a string. Because I have a whole bunch of smilies, using str_replace() ceases to be an option. I have to use one command that will look through the whole string for all the smilies at the same time. I guess preg_replace() would be my #1 option. The problem is, I know zero when it comes to regex, so any help is very much appreciated. I want to recognize smilies with or witiout a space between the smilie and the next character (and previous character) (for instance: "text =)", "text=)", "te=)xt" or "=)text", the :\ part should be recognized as a smilie. My smilie codes include ":eek", ":\", ";)", ":evil" and so fourth. I'm not asking for someone to "do it for me", but please show me how to do it for at least one or two smilies. I hope I'll be able to figure out the rest.

Thanks for the help. :)

Posted: Thu Sep 08, 2005 11:31 pm
by feyd
something like the following:

Code: Select all

function replaceFun($match)
{
  $smilies = array(':)'=>'grin',':evil:'=>'evil');
  if(isset($smilies[$match[0]])) return '<img src="smilies/path/'.$smilies[$match[0]].'.png" />';
  return $match[0];
}

$smilies = array(':)',':evil:');
// make them safe for preg
$safeSmiles = array_map('preg_quote',$smilies);
$text = preg_replace_callback('#'.implode('|',$safeSmiles).'#is','replaceFunc',$text);

Posted: Fri Sep 09, 2005 10:20 am
by evilmonkey
Callback function, now why didn't I think of that? And the regex isn't so bad. Thanks a lot feyd, works like a charm. :)