-1

So lets say I have a link like this:

http://mywebsite.com/profile/alexkvazos/

I would like to explode the url and get this:

$uri = array('profile','alexkvazos');

What is the easiest approach to this?

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126

4 Answers4

1

try

// if the url is http://www.example.com/foo/bar/wow
 function getUriSegments() {
    return explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
 }

    print_r(getUriSegments()); //returns array(0=>'foo', 1=>'bar', 2=>'wow')

Source :- http://www.timwickstrom.com/server-side-code/php/php-get-uri-segments/

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
0

Use parse_url()

$path_parts = parse_url('http://mywebsite.com/profile/alexkvazos/');
$uri = explode('/',trim($path_parts['path'],'/'));
print_r($uri);

Working Demo

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Here you are giving me the URL already on the parse_url function. How would I get it from the URL on the browser? –  May 01 '14 at 06:05
  • 1
    Read $_SERVER manual of PHP http://www.php.net/manual/en/reserved.variables.server.php – Rohit Choudhary May 01 '14 at 06:09
  • Check this [answer](http://stackoverflow.com/a/6768831/1003917) on how to get your URL. Grab that and into a string and pass it into the `parse_url()` function as shown. @RohitKumarChoudhary, Thanks for the link. – Shankar Narayana Damodaran May 01 '14 at 06:10
0

You could use this piece of code:

<?php

$url = 'http://mywebsite.com/profile/alexkvazos/';

$url = rtrim($url,'/'); // lose the trailing slash
$urlArr = explode("/", $url );
$urlArr = array_reverse( $urlArr );

echo $urlArr[0];

?>
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
-1

I wouldn't use parse_url, I would just use preg_split like this:

$segments = preg_split('#/#', $_SERVER['REQUEST_URI']);

$final = array();

foreach($segments as $key => $value) {
    if($value != '') {
        $final[] = $value;
    }
}


var_dump($final);
Ryan
  • 14,392
  • 8
  • 62
  • 102