Example user input
http://domain.com/
http://domain.com/topic/
http://domain.com/topic/cars/
http://www.domain.com/topic/questions/
I want
I'd suggest using the tools PHP gave you, have a look at parse_url.
<?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
It sounds like you're after at least host
+ path
(add others as needed, e.g. query
):
$parsed = parse_url('http://www.domain.com/topic/questions/');
echo $parsed['host'], $parsed['path'];
> www.domain.com/topic/questions/
Cheers
ereg_replace
is now deprecated, so it is better to use:
$url = preg_replace("(^https?://)", "", $url );
This removes either http://
or https://
<?php
// user input
$url = 'http://www.example.com/category/website/wordpress/wordpress-security/';
$url0 = 'http://www.example.com/';
$url1 = 'http://www.example.com/category/';
$url2 = 'http://www.example.com/category/website/';
$url3 = 'http://www.example.com/category/website/wordpress/';
// print_r(parse_url($url));
// echo parse_url($url, PHP_URL_PATH);
$removeprotocols = array('http://', 'https://');
echo '<br>' . str_replace($removeprotocols,"",$url0);
echo '<br>' . str_replace($removeprotocols,"",$url1);
echo '<br>' . str_replace($removeprotocols,"",$url2);
echo '<br>' . str_replace($removeprotocols,"",$url3);
?>
Wow. I came here from google expecting to find a one liner to copy and paste!
You don't need a function to do this because one already exists. Just do:
echo explode("//", "https://anyurl.any.tld/any/directory/structure", 2)[1];
In this example, explode() will return an array of:
["https:", "anyurl.any.tld/any/directory/structure"]
And we want the 2nd element. This will handle http, https, ftp, or pretty much any URI, without needing regex.
https://www.php.net/manual/en/function.explode.php
If you want a function:
function removeProtocols($uri) { return explode("//", $uri, 2)[1]; }
EDIT: See user comment from Harry Lewis... this is my favourite way to do this now.