Anay Bose
Anay Bose

Reputation: 890

Retrieve 'id' from an URL using regular expression

I need to extract only the 'id' from an URL. The url format is given below. Currently, I use parse_url and substr function, which works. However, it is not a good choice if the length of 'id' changes, where regex comes into play. I am not well-conversant with regex, so I need an idea how to do it in other way e.g. regex.

$url = 'http://www.example.com/stock-footage/53833534/portrait-lifestyle-leisure-caucasian-parents-children-snow-v.html'; 
$URLParts = parse_url($url);
// echo $URLParts['path'];  
$substring = substr($URLParts['path'],15,8);
echo $substring; 

Upvotes: 0

Views: 218

Answers (2)

Mahdi Youseftabar
Mahdi Youseftabar

Reputation: 2352

you can use this :

<?php

$url = 'http://www.example.com/stock-footage/53833534/portrait-lifestyle-leisure-caucasian-parents-children-snow-v.html'; 
$URLParts = parse_url($url);

$exploded = explode('/',$URLParts['path']);

echo $exploded[2]; 

?>

Upvotes: 1

m.s.
m.s.

Reputation: 16334

You can use the following regular expression:

preg_match("/.+\/([0-9]+).+/", $url, $matches);
echo $matches[1];

live example

Upvotes: 2

Related Questions