Home » Php » php – Get second segment from url

php – Get second segment from url

Posted by: admin April 23, 2020 Leave a comment

Questions:

How to get the second segment in URL without slashes ?
For example I have a URL`s like this

http://foobar/first/second

How to get the value where “first” stands ?

How to&Answers:

Use parse_url to get the path from the URL and then use explode to split it into its segments:

$uri_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri_segments = explode('/', $uri_path);

echo $uri_segments[0]; // for www.example.com/user/account you will get 'user'

Answer:

$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));

Answer:

To take your example http://domain.com/first/second

$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
$numSegments = count($segments); 
$currentSegment = $segments[$numSegments - 1];

echo 'Current Segment: ' , $currentSegment;

Would result in Current Segment: second

You can change the numSegments -2 to get first

Answer:

Here’s my long-winded way of grabbing the last segment, inspired by Gumbo’s answer:

// finds the last URL segment  
$urlArray = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $urlArray);
$numSegments = count($segments); 
$currentSegment = $segments[$numSegments - 1];

You could boil that down into two lines, if you like, but this way makes it pretty obvious what you’re up to, even without the comment.

Once you have the $currentSegment, you can echo it out or use it in an if/else or switch statement to do whatever you like based on the value of the final segment.