感谢@ s.d.a.p.e我已经走近了一步,但我还没到那里。
我尝试做的是替换文本块中字符串的所有实例。我想替换这样的东西:
user is ?user_id=34&first_name=Ralph so is ?user_id=1 also
有了这个:
user is /user/34/ so is /user/1/ also
以下是我使用的preg_replace代码:
$pattern = '#\?user_id=([0-9]+)#';
$replace = '/user/$1/';
echo preg_replace($pattern,$replace,$string);
有了这种模式,我最终得到了这个:
user is /user/34/&first_name=Ralph so is /user/1/ also
再次感谢。
答案 0 :(得分:1)
print preg_replace(
'#\?user_id=([0-9]+)\&(first_name=(?:.*))#',
'/user/$1?$2',
'?user_id=34&first_name=Ralph'
);
结果:
/user/34?first_name=Ralph if get it right..
答案 1 :(得分:1)
试试这个:
$string = "user is ?user_id=34&first_name=Ralph so is ?user_id=1 also";
$result = preg_replace('/\?(user)_id=(\d+)(.*?)(?! )/i', '/$1/$2/$3', $string );
echo $result ;
输出:
user is /user/34/&first_name=Ralph so is /user/1/ also
答案 2 :(得分:1)
我会用这个:
$string = 'user is ?user_id=34&first_name=Ralph so is ?user_id=1 also';
$pattern = '#\?user_id=([0-9]+)\S*#';
$replace = '/user/$1/';
echo preg_replace($pattern, $replace, $string);
\S
代表任何不是空格的字符。
<强>输出:强>
user is /user/34/ so is /user/1/ also