tags:

views:

46

answers:

3

I am trying to get the ID from a URL string.

I'm trying with the following code:-

FROM:

<url>http://www.monkeys.com/monkey.php?id=24&lt;/url&gt;

I want to get '24' with:-

$ID = preg_replace($url, '/^<url>.*\?id=(.*)<\/url>$/', '\1');

Any help would be much appreciated - i'm sure this is a regular problem, but I find regex baffling.

A: 

you can use this regex:

/^[^?]+\?id=(.*).*$/
catwalk
`(.*)` will just match everything left, your last `.*` is pointless.
Wim
+3  A: 

Regex is the wrong tool for the job. Use

  • parse_strParses the string into variables and
  • parse_urlParse a URL and return its components

Example:

$url = "http://www.monkeys.com/monkey.php?id=24";
parse_str(parse_url($url, PHP_URL_QUERY), $parts);
var_dump( $parts ); // 24

Getting the URL out of the <URL> element should be trivial. DOM is your friend. See the various other questions dealing with Reading XML with PHP and also this article why you should not use Regex for parsing HTML.

Gordon
For some reason, I'm not getting it...$url = http://www.test.com/tester.php?id=212parse_str($url, $parts);echo $parts['id'] = nothing.
WiseDonkey
Works now, didn't follow your example properly. :/ Thanks
WiseDonkey
+1  A: 

If ID is numeric only :

/\?id=(\d+)/

If there's nothing after ID

/\?id=(.*)/
M42
What if there's another argument after it?
Wim
M42
Wim
M42