用正则替换文章中的表情(例如微博)

看到sina微博发出的表情,直接就能显示。正好咱们公司也须要这种效果,我就把代码贴出来,共享!!express

实现的最终效果:ide

原来的句子是这样的“[biggrin]法师打发斯蒂芬[fendou]范德萨发生大幅说的”,经过正则来替换“[]”这些内容,“biggrin”和“fendou”是图片的名字。大概说这么多!下面直接上代码:函数

  
  
  
  
  1. function format($content,$url=false){ 
  2.     return preg_replace_callback("/(?:#[^#]*[^#^\s][^#]*#|(\[.+?\]))/is", replaceEmot, $content); 
  3.  
  4. /* 
  5.  *  表情替换 
  6.  *  @ Lily  
  7.  */  
  8. function replaceEmot($data) { 
  9.     if(preg_match("/#.+#/i",$data[0])) { 
  10.         return $data[0]; 
  11.     } 
  12.     $file = array_pop(explode('['$data[0])); 
  13.     $name = array_shift(explode(']'$file)); 
  14.     if($name) { 
  15.         return preg_replace("/\[.+?\]/i","<img src='/Public/p_w_picpaths/expression/".$name.".gif' />",$data[0]); 
  16.     }else { 
  17.         return $data[0]; 
  18.     } 

这样写好,直接调用format()函数把内容传过来就能够实现你要的效果了!url