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</url>
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.
Regex is the wrong tool for the job. Use
parse_str— Parses the string into variables andparse_url— Parse a URL and return its componentsExample:
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.