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

时间:2013-11-10 13:12:16

标签: php regex

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

INPUT:example.com?q=123123?name=shreyas&city=surat#anchor1

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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-1)

为避免在另一个单词中匹配“is”,您可以使用单词边界\b

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

答案 2 :(得分:-1)

试试这个:

<?php

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

?>

Demo!

对于你的第二个问题:

<?php

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

?>

注意:使用&amp;而不是&amp;如果要将结果显示给用户。