如何使用 PHP 从字符串中替换第二个匹配字符或字符串


how to replace second match character OR string from string using PHP?

如何使用PHP从字符串中替换第二个匹配字符或字符串?

输入:例子.com?q=123123?name=shreyas&city=surat#anchor1

输出 : 例子.com?q=123123?name=shreyas&city=surat#anchor1

 $first = strpos($url , '?'); // find first occurance
 $str = substr($url , 0 ,$first+1); remove first part 
 preg_replace('/'sis's/i', 'XXX' , $str);
为了避免在

另一个单词中匹配"is",您可以使用单词边界'b

$result = preg_replace('/'bis'b/i' , 'xxx', $str);

试试这个:

<?php
$result = preg_replace('/'bis'b/i' , 'xxx', $str);
?>

演示!

对于你的第二个问题:

<?php
$result = preg_replace('/(?<!com)'?/' , '&', $url); 
?>

注意:如果要向用户显示结果,请使用 & 而不是 &。