Can someone tell me how to strip anything that appears between http:// and /? For example, http://something/ or http://something.something.something/ so it changes to just /?
7 Answers
Assuming you're working with a URL and not a long string containing a url...
$path = parse_url($url, PHP_URL_PATH);
1 Comment
You could use parse_url but then you would have to re-build the rest of the URL with different components:
$components = parse_url($url);
$result = $components['path'] . '?' .
$components['query'] . '#' .
$components['fragment'];
1 Comment
$components = parse_url($url); $result = $components['path'] . (!empty($components['query']) ? '?' . $components['query'] : '') . (!empty($components['fragment']) ? '#' . $components['fragment'] : '');The following will simply return the Path of your URL:
<?php
$urls = array(
'http://something.com/',
'http://something.something.com/',
'http://something.something.com/some/path',
'http://something.something.com/some/path/?query=string',
'http://something.something.com/some/path/?query=string#with-fragment',
);
foreach ($urls as $url) {
var_dump(parse_url($url, PHP_URL_PATH));
}
#=> string(1) "/"
#=> string(1) "/"
#=> string(10) "/some/path"
#=> string(11) "/some/path/"
#=> string(11) "/some/path/"
Note, if you're just looking to strip the URL Scheme and the Host off the URL, and you want to keep the Query and the Fragment, you can use this:
foreach ($urls as $url) {
$url = parse_url($url);
$ret = $url['path'];
if ($url['query']) $ret .= "?{$url[query]}";
if ($url['fragment']) $ret .= "#{$url[fragment]}";
var_dump($ret);
}
#=> string(1) "/"
#=> string(1) "/"
#=> string(10) "/some/path"
#=> string(24) "/some/path/?query=string"
#=> string(38) "/some/path/?query=string#with-fragment"
Better yet, If you're using the PECL HTTP Extension, you can use the http_build_url() method:
foreach ($urls as $url) {
$url = http_build_url(array_key_intersect(
parse_url($url),
array_flip(array('path', 'query', 'fragment'))
));
var_dump($url);
}
#=> string(1) "/"
#=> string(1) "/"
#=> string(10) "/some/path"
#=> string(24) "/some/path/?query=string"
#=> string(38) "/some/path/?query=string#with-fragment"
Comments
$url = "http://php.net/manual/en/function.parse-url.php?arg=value#anchor";
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
The above example will output:
Array
(
[scheme] => http
[host] => php.net
[path] => /manual/en/function.parse-url.php
[query] => arg=value
[fragment] => anchor
)
please refer to parse-url
Specify one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT to retrieve just a specific URL component as a string (except when PHP_URL_PORT is given, in which case the return value will be an integer).
Comments
What you want appears to be the $_SERVER['REQUEST_URI']. Or you can get that with parse_url()
Or if you insist on using regex, [EDIT] don't.