首頁 >後端開發 >php教程 >為什麼str_replace回傳的資料錯誤

為什麼str_replace回傳的資料錯誤

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB原創
2016-08-04 09:19:151575瀏覽

例:替換英文逗號,空格字符,或中文逗號
$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%

回覆內容:

例:替換英文逗號,空格字符,或中文逗號
$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%

先把空格替換成其他字元 $str在替換的過程中,=》 %, or username like % ,這裡面也存在滿足你替換規則的字符串所以會影響到結果

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

</code>

注意:由於str_replace()函數替換左到右,它可能會進行多次替換時替換先前插入的值。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn