2011-04-08 45 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