看到sina微博发出的表情,直接就能显示。正好我们公司也需要这种效果,我就把代码贴出来,共享!!
实现的最终效果:
原来的句子是这样的“[biggrin]法师打发斯蒂芬[fendou]范德萨发生大幅说的”,通过正则来替换“[]”这些内容,“biggrin”和“fendou”是图片的名字。大概说这么多!下面直接上代码:
- function format($content,$url=false){
- return preg_replace_callback("/(?:#[^#]*[^#^\s][^#]*#|(\[.+?\]))/is", replaceEmot, $content);
- }
- /*
- * 表情替换
- * @ Lily
- */
- function replaceEmot($data) {
- if(preg_match("/#.+#/i",$data[0])) {
- return $data[0];
- }
- $file = array_pop(explode('[', $data[0]));
- $name = array_shift(explode(']', $file));
- if($name) {
- return preg_replace("/\[.+?\]/i","<img src='/Public/p_w_picpaths/expression/".$name.".gif' />",$data[0]);
- }else {
- return $data[0];
- }
- }
这样写好,直接调用format()函数把内容传过来就可以实现你要的效果了!
转载于:https://blog.51cto.com/jsny821/960370