-1

Possible Duplicate:
Replace a list of emoticons with their images

i'm developing a website where i want to give users possibility to put smiles on posts. My (just functional) idea is to use array in this way:

$emoticons = array(
array("17.gif",":)"),
array("6.jpg",":P"),
.....
array("9.jpg",":'("),
array("5.gif","X)")
);

with image on [0] and emoticon on [1]. And on each $post:

foreach($emoticons as $emoticon){
     $quoted_emoticon = preg_quote($emoticon[1],"#");
     $match = '#(?!<\w)(' . $quoted_emoticon .')(?!\w)#';
     $post = preg_replace($match,'<img src="images/emoticons/'.$emoticon[0].'">',$post);
}

This is working good, but my problem is '#(?!<\w)(' and ')(?!\w)#' because I want emoticons to apply only when preceding characters are "begin" (^) or "blank" and succeeding characters are "end" ($) or "blank". What is the right regex to do this?

Community
  • 1
  • 1
Giuseppe Donato
  • 147
  • 2
  • 15

2 Answers2

1

I think you want the positive look behind and positive look ahead.

Example:

(?<=\s|^)(\:\))(?=\s|$)

Your example updated:

foreach($emoticons as $emoticon){
     $quoted_emoticon = preg_quote($emoticon[1],"#");
     $match = '(?<=\s|^)(' . $quoted_emoticon .')(?=\s|$)';
     $post = preg_replace($match,'<img src="images/emoticons/'.$emoticon[0].'">',$post);
}
used2could
  • 4,956
  • 2
  • 27
  • 30
0

I would go with:

$e = array( ':)' => '1.gif',
            ':(' => '2.gif',
          );

foreach ($e as $sign => $file) { 
  $sign = preg_replace('/(.)/', "\\$1", $sign); 
  $pattern = "/(?<=\s|^)$sign(?=\s|$)/";
  $post = preg_replace($pattern, " <img src=\"images/emoticons/$file\">", $post);  
} 
Ωmega
  • 40,237
  • 31
  • 123
  • 190
  • No, you didn't understand or i was not able to explain the problem: I want to apply replace ONLY when preceding/succeeding char is BLANK (or they are ^|$, that means begin/end) My data structure already work! I have no problem replacing... i want to limit WHEN to replace! – Giuseppe Donato Jun 24 '12 at 17:22
  • if someone write: Hello, my name is Ralph ;-) OK. If some write: Hello, my name is Ralph;-) NO Understand? – Giuseppe Donato Jun 24 '12 at 17:24