I need to replace textual emoticons to html image tags. I compiled the following data:
private $smile = array(">:]", ":-)", ":)", ":o)", ":]", ":3", ":c)", ":>", "=]", "8)", "=)", ":}", ":^)");
private $laugh = array(">:D", ":-D", ":D", "8-D", "x-D", "X-D", "=-D", "=D", "=-3", "8-)");
private $sad = array(">:[", ":-(", ":(", ":-c", ":c", ":-<", ":-[", ":[", ":{", ">.>", "<.<", ">.<");
private $wink = array(">;]", ";-)", ";)", "*-)", "*)", ";-]", ";]", ";D", ";^)");
private $tongue = array(">:P", ":-P", ":P", "X-P", "x-p", ":-p", ":p", "=p", ":-Þ", ":Þ", ":-b", ":b", "=p", "=P");
private $surprise = array(">:o", ">:O", ":-O", ":O", "°o°", "°O°", ":O", "o_O", "o.O", "8-0");
private $annoyed = array(">:\\", ">:/", ":-/", ":-.", ":\\", "=/", "=\\", ":S");
private $cry = array(":'(", ";'(");
private $t_smile = "<img class=\"smiley\" src=\"/images/emoticons/smile.png\"/>";
private $t_laugh = "<img class=\"smiley\" src=\"/images/emoticons/laugh.png\"/>";
private $t_sad = "<img class=\"smiley\" src=\"/images/emoticons/sad.png\"/>";
private $t_wink = "<img class=\"smiley\" src=\"/images/emoticons/wink.png\"/>";
private $t_tongue = "<img class=\"smiley\" src=\"/images/emoticons/tongue.png\"/>";
private $t_surprise = "<img class=\"smiley\" src=\"/images/emoticons/surprise.png\"/>";
private $t_annoyed = "<img class=\"smiley\" src=\"/images/emoticons/annoyed.png\"/>";
private $t_cry = "<img class=\"smiley\" src=\"/images/emoticons/cry.png\"/>"
I am currently simply doing for example:
$str = str_replace($this->laugh, $this->t_laugh, $str);
for each group. It works fine but I need the replacement to occur only if the words are not surrounded by letters or other digits. In other words, I need to compile a regex which contain each emoticon array so that I can use preg_replace instead of str_replace. Is there a way I can do this easily instead of hardcoding the regex and escaping all the necessary characters?
EDIT:
Also, I need to match and replace the emoticons which appear in the beginning and end of a string, so a simple padding with a space technique won't suffice.
EDIT 2:
I followed Mark's example and pre-compiled the regex from the arrays using preg_quote as:
private $smile = "#(^|\W)(\>\:\]|\:-\)|\:\)|\:o\)|\:\]|\:3|\:c\)|\:\>|\=\]|8\)|\=\)|\:\}|\:\^\))($|\W)#";
private $laugh = "#(^|\W)(\>\:D|\:-D|\:D|8-D|x-D|X-D|\=-D|\=D|\=-3|8-\)|xD|XD|8D|\=3)($|\W)#";
private $sad = "#(^|\W)(\>\:\[|\:-\(|\:\(|\:-c|\:c|\:-\<|\:-\[|\:\[|\:\{|\>\.\>|\<\.\<|\>\.\<)($|\W)#";
private $wink = "#(^|\W)(\>;\]|;-\)|;\)|\*-\)|\*\)|;-\]|;\]|;D|;\^\))($|\W)#";
private $tongue = "#(^|\W)(\>\:P|\:-P|\:P|X-P|x-p|\:-p|\:p|\=p|\:-Þ|\:Þ|\:-b|\:b|\=p|\=P|xp|XP|xP|Xp)($|\W)#";
private $surprise = "#(^|\W)(\>\:o|\>\:O|\:-O|\:O|°o°|°O°|\:O|o_O|o\.O|8-0)($|\W)#";
private $annoyed = "#(^|\W)(\>\:\\|\>\:/|\:-/|\:-\.|\:\\|\=/|\=\\|\:S|\:\/)($|\W)#";
private $cry = "#(^|\W)(\:'\(|;'\()($|\W)#";
Works perfectly with preg_replace!