Bit of regex advice - smilies

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Bit of regex advice - smilies

Post 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. :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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);
User avatar
evilmonkey
Forum Regular
Posts: 823
Joined: Sun Oct 06, 2002 1:24 pm
Location: Toronto, Canada

Post 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. :)
Post Reply