Home  >  Article  >  Backend Development  >  求解关于preg_replace函数解决思路

求解关于preg_replace函数解决思路

WBOY
WBOYOriginal
2016-06-13 11:19:561003browse

求解关于preg_replace函数
我想使用preg_replace函数把text里面的部分字符替换成图片
当我这样写时可以正常执行

<br />$expression ="[email&#160;protected]/";<br />$reexpression ="呲牙";<br />$text=preg_replace($expression,'<img  src="www.test.com/static/expression/'.$reexpression.'.gif" / alt="求解关于preg_replace函数解决思路" > ',$text);

可是当我改成数组后替换后图片的url都成了www.test.com/static/expression/Array.gif了
<br />$expression =array("[email&#160;protected]/","[email&#160;protected]/","[email&#160;protected]/");<br />$reexpression =array("呲牙","鄙视","折磨");<br />$text=preg_replace($expression,'<img  src="www.test.com/static/expression/'.$reexpression.'.gif" / alt="求解关于preg_replace函数解决思路" > ',$text);

我刚接触php,希望大家能帮忙看一下


------解决方案--------------------
在执行函数前会先计算出参数的值。因此也就是:
$replace = '求解关于preg_replace函数解决思路 ';
$text = preg_replace($expression, $replace, $text);
// 由于 $reexpression 是个数组,因此数组和字符串相连就会是Array.gif

看你的需求,重新写一下:
$text = [email&#160;protected],->@鄙视<-';<br />$reexpression =array("呲牙","鄙视","折磨");<br />// 希望你的程序最好以UTF-8编码,u修饰符的作用就是避免编码出现意外的混乱<br />$find = '#@('. join('<br><font color='#FF8000'>------解决方案--------------------</font><br>', $reexpression) .')#u';<br />$replace = '<img src="www.test.com/static/expression/$1.gif" alt="$1"/>';<br />$text = preg_replace($find, $replace, $text);

另外你的图片以中文命名,还需要注意可能在IE下产生的编码问题,导致图片加载404错误

附手册: http://php.net/preg-replace
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn