使用 PHP 获取 URL 的一部分


Get part of URL with PHP

我有一个网站,我需要用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