我有一个站点,我需要使用 PHP 获取一个页面 URL。URL 可能是某物www.mydomain.com/thestringineed/
,也可能是www.mydomain.com/thestringineed?data=1
,也可能是www.mydomain.com/ss/thestringineed
所以它总是最后一个字符串,但我不想在之后得到任何东西?
parse_url
应该可以帮助你。
<?php
$url = "http://www.mydomain.com/thestringineed/";
$parts = parse_url($url);
print_r($parts);
?>
您将使用 parse_url 函数,然后查看返回的路径部分。像这样:
$url='www.mydomain.com/thestringineed?data=1';
$components=parse_url($url);
//$mystring= end(explode('/',$components['path']));
// I realized after this answer had sat here for about 3 years that there was
//a mistake in the above line
// It would only give the last directory, so if there were extra directories in the path, it would fail. Here's the solution:
$mystring=str_replace( reset(explode('/',$components['path'])),'',$components['path']); //This is to remove the domain from the beginning of the path.
// In my testing, I found that if the scheme (http://, https://, ...) is present, the path does not include
//the domain. (it's available on it's own as ['host']) In that case it's just
// $mystring=$components['path']);
parse_url()
是您正在寻找的功能。您想要的确切部分,可以通过PHP_URL_PATH
$url = 'http://php.net/manual/en/function.parse-url.php';
echo parse_url($url, PHP_URL_PATH);
使用$_SERVER['REQUEST_URI']
它将返回完整的当前页面 url,您可以使用 '/' 拆分它并使用最后一个数组索引。这将是最后一个字符串
您可以使用:
$strings = explode("/", $urlstring);
这将删除 url 中的所有 '/' 并返回一个包含所有单词的数组。
$strings[count($strings)-1]
现在有了您需要的字符串的值,但它可能包含 '?data=1' 所以我们需要删除它:
$strings2 = explode("?", $strings[count($strings)-1]);
$strings2[0]
有你想要的 url 中的字符串。
希望这可以帮助!
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
你的输出是
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
/path