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?
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?
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
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
/matt not mattYou could use the parse_url function, this will return an array with all the information about the URL. Something like this is probably what you would like:
echo explode('/', parse_url('http://www.shareit.me/matt')['path'])[1];
foo.com/matt/images? I imagine he's trying to get a username or something from the URL.$url = "http://www.shareit.me/matt";
$parts = Explode('/', $url);
$id = $parts[count($parts) - 1];
By the way Getting a part from a string.
If you want to get the url that is used to browse to the script, you use the $_SERVER['REQUEST_URI'] variable.
In your case it will return this:
/matt
But you'll need to filter out the information you actual need.
For that you can use preg_match or an alternative way.
For more information about the $_SERVER variable: see this page
If you want to get information of a string that contains a url, you can use
explode("/", $url);
you can use regex with preg_match
preg_match("/.\/(.*)$/",$url,$matches);
than check matches if it contains what you want