Home  >  Article  >  Backend Development  >  关于preg_replace十分不解的事情

关于preg_replace十分不解的事情

WBOY
WBOYOriginal
2016-06-13 11:50:24758browse

关于preg_replace非常不解的事情?

本帖最后由 yyixin 于 2014-03-02 15:12:06 编辑
<br /><br />$thumbMark = '200x200';<br />$thumb =$r['thumb'];<br />echo $r['thumb'].'<br />'; // http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_100x100.jpg<br />                //$thumb='http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_100x100.jpg';<br />$r['thumb'] = preg_replace('/_\d+x\d+/', '_' . $thumbMark,$thumb);<br />echo $r['thumb'].'<br />'; // http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_100x100.jpg<br /><br /><br /><br /><br /><br />


为何上述的替换函数无效,而如下给“$thumb”直接赋值,却能正常替换?

<br /><br />$thumbMark = '200x200';<br />$thumb =$r['thumb'];<br />echo $r['thumb'].'<br />'; // http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_100x100.jpg<br />$thumb='http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_100x100.jpg';<br />$r['thumb'] = preg_replace('/_\d+x\d+/', '_' . $thumbMark,$thumb);<br />echo $r['thumb'].'<br />'; // http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_200x200.jpg<br /><br /><br /><br /><br /><br />




------解决方案--------------------
var_dump($r['thumb']);
贴出结果
------解决方案--------------------
引用:
发现一点端倪了,将正则“/_\d+x\d+/”中间的x去除之后,能正常替换,输出“http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_200x200x100.jpg”;

真是太奇怪了,这个“x”到底招谁惹谁了?

那说明你的正则是有问题的
------解决方案--------------------
引用:
Quote: 引用:

var_dump($r['thumb']);
贴出结果



string(85) "http://img2.com.cn/images/2014/038/422/14058002224830.9000001763_100x100.jpg"

你这个字串只有76个字符,为何是string(85) ?
------解决方案--------------------
正则这种东西 搞不定的话 只能从源头开始了
$str = '_100x100.jpg';
echo preg_replace('/_/', '', $str);
echo preg_replace('/_\d+/', '', $str);
echo preg_replace('/_\d+x/', '', $str);
echo preg_replace('/_\d+x\d+/', '', $str);
看看哪个有问题 看懂的话就去试试吧...
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