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

求解关于preg_replace函数

WBOY
WBOYOriginal
2016-06-23 14:05:07919browse

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

$expression ="/@呲牙/";$reexpression ="呲牙";$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了
$expression =array("/@呲牙/","/@鄙视/","/@折磨/");$reexpression =array("呲牙","鄙视","折磨");$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 = '别@呲牙了,->@鄙视<-';$reexpression =array("呲牙","鄙视","折磨");// 希望你的程序最好以UTF-8编码,u修饰符的作用就是避免编码出现意外的混乱$find = '#@('. join('|', $reexpression) .')#u';$replace = '<img src="www.test.com/static/expression/$1.gif" alt="$1"/>';$text = preg_replace($find, $replace, $text);

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

附手册:  http://php.net/preg-replace

在执行函数前会先计算出参数的值。因此也就是:
$replace = '求解关于preg_replace函数 ';
$text = preg_replace($expression, $replace, $text);
// 由于 $reexpression 是个数组,因此……
非常感谢,终于好了

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