繁体   English   中英

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

[英]How to get a string from url using preg_match?

我想使用php preg_match从url中提取id ..

例如: $string = 'http://www.mysite.com/profile.php?id=1111'; : $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 '

有人能帮助我吗?

为什么不在parse_str使用parse_url

$url_component = parse_url($string);
parse_str($url_component['query'], $output);
echo $output['id'];
$pattern = '/(?:https?):\/\/www\.mysite\.com\/profile\.php\?id\=([0-9]+)/';

这应该工作正常! 但是使用parse_url执行此操作

如果url中只有一个参数,你可以使用explode函数轻松完成,比如

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

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

希望这有帮助,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM