简体   繁体   English

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

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

I want to extract id from an url using php preg_match.. 我想使用php preg_match从url中提取id ..

For eg: $string = 'http://www.mysite.com/profile.php?id=1111'; 例如: $string = 'http://www.mysite.com/profile.php?id=1111'; : $string = 'http://www.mysite.com/profile.php?id=1111'; I need output as '1111' 我需要输出'1111'

using preg_match. 使用preg_match。

I tried this : 我试过这个:

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

    $id =  $match[1];
}

But am getting output as ' profile.php ' 但我输出为' profile.php '

Can someone help me please? 有人能帮助我吗?

Why not use parse_url with parse_str 为什么不在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]+)/';

This should work fine! 这应该工作正常! But do this with parse_url 但是使用parse_url执行此操作

if there is only one parameter in the url you can use explode function to do that easily, like 如果url中只有一个参数,你可以使用explode函数轻松完成,比如

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

You may also use parse_url function of php. 你也可以使用php的parse_url函数。

Hope this help, 希望这有帮助,

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

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