Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting Information from URL with PHP

I would like to use PHP to extract the information from a url. How can I get the value "matt" from the url:

www.shareit.me/matt 

Also, how can I possibly check to see if there is a value there to begin with?

like image 805
user2096890 Avatar asked Jul 29 '26 18:07

user2096890


2 Answers

No need to over-complicate things here:

$url  = 'www.shareit.me/matt';
$segs = explode('/', $url);
echo $segs[1]; // matt

Checking to see if it exists is as simple as if ( !empty($segs[1]) ) {}

Assuming you want the value matt and not just the "path", this will work with all these:

www.shareit.me/matt // matt
www.shareit.me/matt/photos
www.shareit.me/matt/photos/vacation/nebraska/cows/ // matt
www.shareit.me/matt/photos?vacation=mexico&gallery=donkeyshow // matt
www.shareit.me/matt/loves/cheese // matt

If you actually want people to know that matt loves cheese, you should use parse_url() instead:

parse_url('www.shareit.me/matt/loves/cheese', PHP_URL_PATH); // /matt/loves/cheese
like image 87
AlienWebguy Avatar answered Aug 01 '26 07:08

AlienWebguy


voila, RTM: http://php.net/manual/en/function.parse-url.php

<?php

$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>

The above example will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path
like image 34
michi Avatar answered Aug 01 '26 07:08

michi