Home >Backend Development >PHP Tutorial >Why str_replace returns wrong data

Why str_replace returns wrong data

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-08-04 09:19:151572browse

Example: Replace English commas, space characters, or Chinese commas
$str = 'Correct, contact us goodsjob, goodsjob';
$reg = array(',',' ',',' );
$strs = ' username like %'.str_replace($reg,'%, or username like %',$str).'%';
The returned data is: username like %correct%,%, or username like %or%, or username like %username%, or username like %like%, or username like % Contact Us%, or username like %goodsjob%, or username like %goodsjob%, why?

The correct result should be: usernme like %correct%, or username like %contact us%, or username like %goodsjob%

Reply content:

Example: Replace English commas, space characters, or Chinese commas
$str = 'Correct, contact us goodsjob, goodsjob';
$reg = array(',',' ',',' );
$strs = ' username like %'.str_replace($reg,'%, or username like %',$str).'%';
The returned data is: username like %correct%,%, or username like %or%, or username like %username%, or username like %like%, or username like % Contact Us%, or username like %goodsjob%, or username like %goodsjob%, why?

The correct result should be: usernme like %correct%, or username like %contact us%, or username like %goodsjob%

First replace the spaces with other characters. During the replacement process, $str =》%, or username like %. There are also strings that meet your replacement rules, so it will affect the result

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

</code>

Note: Since the str_replace() function replaces left to right, it may replace previously inserted values ​​when doing multiple replacements.

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