2011-04-08 83 views
11

我需要解析当前的URL,这样,在这两种情况下:PHP - 解析当前URL

http://mydomain.com/abc/ 
http://www.mydomain.com/abc/ 

我能得到的“ABC”的返回值(或任何文本是在那个位置) 。我怎样才能做到这一点?

回答

34

您可以使用parse_url();

$url = 'http://www.mydomain.com/abc/'; 

print_r(parse_url($url)); 

echo parse_url($url, PHP_URL_PATH); 

这将使你

Array 
(
    [scheme] => http 
    [host] => www.mydomain.com 
    [path] => /abc/ 
) 
/abc/ 

更新:获得当前页面的URL,然后分析它:

function curPageURL() { 
$pageURL = 'http'; 
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} 
$pageURL .= "://"; 
if ($_SERVER["SERVER_PORT"] != "80") { 
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; 
} else { 
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; 
} 
return $pageURL; 
} 

print_r(parse_url(curPageURL())); 

echo parse_url($url, PHP_URL_PATH); 

source for curPageURL function

+0

谢谢你,但有没有办法从自动获取当前的URL浏览器吗?我无法对其进行硬编码。 – sol 2011-04-08 17:18:56

+0

@sol更新为包括获取当前页面的网址 – kjy112 2011-04-08 17:31:30

+0

我有一个问题,如果你不使用http://在url中怎么办如果我只是mydomain.com/abc/,我试过但它只返回路径。 – 2014-12-16 21:06:32

8

查看parse_url()函数。它会将你的URL分解成它的组成部分。你关注的部分是路径,所以你可以通过PHP_URL_PATH作为第二个参数。如果您只想要路径的第一部分,则可以使用explode()将其分割为/作为分隔符。

$url = "http://www.mydomain.com/abc/"; 
$path = parse_url($url, PHP_URL_PATH); 
$pathComponents = explode("/", trim($path, "/")); // trim to prevent 
                // empty array elements 
echo $pathComponents[0]; // prints 'abc' 
4

若要检索当前的URL,你可以,如果你想匹配究竟什么是第一和路径的第二/之间,尝试直接$_SERVER['REQUEST_URI']使用使用类似$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

<?php 

function match_uri($str) 
{ 
    preg_match('|^/([^/]+)|', $str, $matches); 

    if (!isset($matches[1])) 
    return false; 

    return $matches[1]; 
} 

echo match_uri($_SERVER['REQUEST_URI']); 

只是为了好玩,与strpos() + substr()而不是preg_match()一个版本,这应该是一个几微秒快:

function match_uri($str) 
{ 
    if ($str{0} != '/') 
    return false; 

    $second_slash_pos = strpos($str, '/', 1); 

    if ($second_slash_pos !== false) 
    return substr($str, 1, $second_slash_pos-1); 
    else 
    return substr($str, 1); 
} 

HTH在浏览器

0
<?function urlSegment($i = NULL) { 
static $uri; 
if (NULL === $uri) 
{ 
    $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); 
    $uri = explode('/', $uri); 
    $uri = array_filter($uri); 
    $uri = array_values($uri); 
} 
if (NULL === $i) 
{ 
    return '/' . implode('/', $uri); 
} 
$i = (int) $i - 1; 
$uri = str_replace('%20', ' ', $uri); 
return isset($uri[$i]) ? $uri[$i] : NULL;} ?> 

样本地址:http://localhost/this/is/a/sample URL

<? urlSegment(1); //this 
urlSegment(4); //sample url?> 
0
<?php 
$url = "http://www.mydomain.com/abc/"; //https://www... http://... https://... 
echo substr(parse_url($url)['path'],1,-1); //return abc 
?> 
1
$url = 'http://www.mydomain.in/abc/'; 

print_r(parse_url($url)); 

echo parse_url($url, PHP_URL_host); 
+0

它不工作 – prakash 2016-09-30 12:49:57