0

I want return specific part of URL by php. for example if URL is :

http://website.com/part1/part2/part3/detail/page_id/number/page/2

or

http://website.com/part1/part2/part3/detail/page_id/number/page/3 

I want return number.

is it okay?

$pattern = "/\d+$/";
$input = "http://website.com/part1/part2/part3/detail/page_id/number/page/2";
preg_match($pattern, $input, $matches);
$post_id = $matches[8];
Mörre
  • 5,699
  • 6
  • 38
  • 63
Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81

3 Answers3

0

I think the id would be in $matches[0]. But this regex pattern would match any url with a number at the end. E.g.

http://differentdomain.com/whatever/7

Maybe that is sufficient for you, if not please describe us your usecase in more detail.

Mario A
  • 3,286
  • 1
  • 17
  • 22
0

use it:

return $id3 = $parts[count($parts) - 3];
Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81
0

PHP provides parse_url() function, that split the url by the components as stated in the RFC 3986

$s = 'http://website.com/part1/part2/part3/detail/page_id/number/page/2';
$u = parse_url($s);

// gives you
array (size=3)
'scheme' => string 'http' (length=4)
'host' => string 'website.com' (length=11)
'path' => string '/part1/part2/part3/detail/page_id/number/page/2' (length=47)

In case you want to only get a specific component, the function can accept a flag as a second parameter (ex. PHP_URL_PATH) that helps on that.

$u = parse_url($s, PHP_URL_PATH);

// gives you
string '/part1/part2/part3/detail/page_id/number/page/2' (length=47)

You can now create an array of the segments, and elaborate your logic with it:

$segments = explode('/',trim($u,'/'));
Community
  • 1
  • 1
ilpaijin
  • 3,645
  • 2
  • 23
  • 26