PHP preg_replace url以字符串形式获取参数

时间:2015-04-16 20:36:19

标签: php regex preg-replace

感谢@ 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

再次感谢。

3 个答案:

答案 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

DEMO

答案 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