0

I want to extract id from an url using php preg_match..

For eg: $string = 'http://www.mysite.com/profile.php?id=1111'; I need output as '1111'

using 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'

Can someone help me please?

asked Aug 9, 2012 at 6:30
3
  • 2
    Why don't you just take it w/ parse_url? Commented Aug 9, 2012 at 6:32
  • You have mistake in regex, id\=[0-9] should be written as id=([0-9]+) Commented Aug 9, 2012 at 6:35
  • @DainisAbols : No i want to check the url name, if its correct only i need the id.. Commented Aug 9, 2012 at 6:43

3 Answers 3

2

Why not use parse_url with parse_str

$url_component = parse_url($string);
parse_str($url_component['query'], $output);
echo $output['id'];
answered Aug 9, 2012 at 6:34

Comments

0

if there is only one parameter in the url you can use explode function to do that easily, like

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

You may also use parse_url function of php.

Hope this help,

answered Aug 9, 2012 at 6:35

Comments

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

This should work fine! But do this with parse_url

answered Aug 9, 2012 at 6:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.