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

Why str_replace returns wrong data

WBOY
Release: 2016-08-04 09:19:15
Original
1544 people have browsed it

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>
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template