使用PHP获取URL的一部分

时间:2012-05-04 12:33:33

标签: php url

我有一个网站,我需要用PHP获取一个页面的URL。该网址可能是www.mydomain.com/thestringineed/,也可以是www.mydomain.com/thestringineed?data=1,也可以是www.mydomain.com/ss/thestringineed

所以它始终是最后一个字符串,但我不想在之后得到任何东西?

6 个答案:

答案 0 :(得分:4)

parse_url可以帮助你。

<?php
   $url = "http://www.mydomain.com/thestringineed/";
   $parts = parse_url($url);

   print_r($parts);
?>

答案 1 :(得分:2)

您将使用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']);

答案 2 :(得分:0)

parse_url()是您正在寻找的功能。您想要的确切部分可以通过PHP_URL_PATH

收到
$url = 'http://php.net/manual/en/function.parse-url.php';
echo parse_url($url, PHP_URL_PATH);

答案 3 :(得分:0)

使用$_SERVER['REQUEST_URI']它将返回完整的当前页面网址,您可以使用“/”将其拆分并使用最后一个数组索引。它将是最后一个字符串

答案 4 :(得分:0)

您可以使用:

$strings = explode("/", $urlstring);

将删除url中的所有'/'并返回包含所有单词的数组。

$strings[count($strings)-1] 

现在有你需要的字符串的值,但它可能包含'?data = 1'所以我们需要删除它:

$strings2 = explode("?", $strings[count($strings)-1]);

$strings2[0] 

您是否想要从网址中删除字符串。

希望这有帮助!

答案 5 :(得分:0)

<?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
相关问题