search

Home  >  Q&A  >  body text

php - 为什么str_replace返回的数据错误

例:替换英文逗号,空格字符,或者中文逗号
$str = '正确,联系我们 goodsjob,goodsjob';
$reg = array(',',' ',',' );
$strs = 'username like %'.str_replace($reg,'%, or username like %',$str).'%';
返回的数据是:username like %正确%,%, or username like %or%, or username like %username%, or username like %like%, or username like %%联系我们%, or username like %goodsjob%, or username like %goodsjob%,为什么呢?

正确的结果应该是:usernme like %正确%, or username like %联系我们%, or username like %goodsjob%

阿神阿神2802 days ago652

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-11 09:44:02

    先把空格替换成其他字符 $str在替换的过程中,=》 %, or username like % ,这里面也存在满足你替换规则的字符串所以会影响到结果

            $str = '正确,联系我们 goodsjob,goodsjob';
            $str = str_replace(' ', ' ', $str);
            $reg = array(',',','," ");
            $strs = 'username like %'.str_replace($reg,'%, or username like %',$str).'%';
            
            
    
    

    注意:由于str_replace()函数替换左到右,它可能会进行多次替换时替换以前插入的值。

    reply
    0
  • Cancelreply