如何使用preg_match从url获取字符串?

时间:2012-08-09 06:30:39

标签: php preg-match

我想使用php preg_match ..

从网址中提取id

例如:$string = 'http://www.mysite.com/profile.php?id=1111';我需要输出为'1111'

使用preg_match。

我试过了:

if(preg_match('/(?:https?):\/\/www\.mysite\.com\/profile\.php\?id\=[0-9]/', $string, $match) > 0){

    $id =  $match[1];
}

但输出为'profile.php'

有人能帮助我吗?

3 个答案:

答案 0 :(得分:2)

为什么不将parse_urlparse_str

一起使用
$url_component = parse_url($string);
parse_str($url_component['query'], $output);
echo $output['id'];

答案 1 :(得分:0)

$pattern = '/(?:https?):\/\/www\.mysite\.com\/profile\.php\?id\=([0-9]+)/';

这应该可以正常工作! 但是使用parse_url

执行此操作

答案 2 :(得分:0)

如果网址中只有一个参数,您可以使用explode功能轻松完成此操作,例如

$string = 'http://www.mysite.com/profile.php?id=1111';
$ex=explode('=',$string);
$id=$ex[1];

您也可以使用php的parse_url函数。

希望得到这个帮助,