Home > Article > Backend Development > PHP regular replacement preg_replace_PHP tutorial
I have a question, how to replace a specific string in a string. Example: Replace abc in the string: abc fdab ertDe fda Abc fdd, where abc is not case-sensitive. After replacement, the string is: fdab ertDe fda fdd
I immediately thought of two strategies: preg_replace and preg_split. Alas, I didn’t have a manual at the time, so I didn’t have the courage to try it. Let’s show the code here. It seems that I really need to pay attention in the future. Let’s code:
[php]
$str = 'abc fdab ertDe fda Abc fdd ';
$pat = '/abc/i';
$rtn = preg_replace($pat, '', $str, -1);
echo 'orig:', $str, '
';
echo 'dest:', $rtn;
$str = 'abc fdab ertDe fda Abc fdd ';
$pat = '/abc/i';
$rtn = preg_replace($pat, '', $str, -1);
echo 'orig:', $str, '
';
echo 'dest:', $rtn; Please click preg_replace to view the usage of the function. Showshowpreg_split again:
[php]
$str = 'abc fdab ertDe fda Abc fdd ';
$pat = '/abc/i';
$arr = preg_split($pat, $str);
$rtn = implode('', $arr);
echo 'orig:', $str, '
';
echo 'dest:', $rtn;
$str = 'abc fdab ertDe fda Abc fdd ';
$tran = array('abc' => '', 'Abc' => '');
$rtn = strtr($str, $tran);
echo 'orig:', $str, '
';
echo 'dest:', $rtn;
$str = 'abc fdab ertDe fda Abc fdd ';
$tran = array('abc' => '', 'Abc' => '');
$rtn = strtr($str, $tran);
echo 'orig:', $str, '
';
echo 'dest:', $rtn;
This method is a bit tricky. It mainly uses strtr to circumvent the rules, which deviates from other people's purposes and is not a good method!
This time, it is time to reflect on the issue of regularity. Although I have learned a lot about regularity and written some. But I always read the manual when using it, keep trying and rewriting, and can't understand it clearly. I feel a little timid about it. I should write more and practice more in the future to truly become familiar with this basic skill.
http://www.bkjia.com/PHPjc/477587.html