PHP替换第二次出现?与&

时间:2016-06-07 04:42:38

标签: php

我有几个字符串,如果字符串如下

$string ="w?w+f=w?wefwef?blahblah";

$desiredString ="w?w+f=w&wefwef?blahblah";

如果这种格式,我试图替换第二个?到&别无所求。

我尝试过regex和preg_match,但没有运气。

2 个答案:

答案 0 :(得分:3)

在您目前的情况下,解决方案是:

$string ="w?w+f=w?wefwef?blahblah";

$desiredString = preg_replace('/^(.+?\?.+?)\?/', '$1&', $string);

echo $desiredString;

输出:

w?w+f=w&wefwef?blahblah

第N次出现RegExp:

/^((?:(?:.*?\?){0}.*?))\?/ // for first occurence
/^((?:(?:.*?\?){1}.*?))\?/ // for second occurence
/^((?:(?:.*?\?){2}.*?))\?/ // for third occurence
                           // etc.

答案 1 :(得分:1)

试试这个:

$string ="w?w+f=w?wefwef?blahblah";
$desiredString = '';
$j = 0;
for($i = 0; $i < strlen($string); $i++){
    if($string[$i] == '?' && ++$j == 2)
        $desiredString .= '&';
    else
        $desiredString .= $string[$i];
}

echo $desiredString; //w?w+f=w&wefwef?blahblah