2015-07-03 86 views
-2

我的URL可以被以下,得到的文件夾名稱

1)www.steptoinstall.com

2)www.steptoinstall.com/folder1

3)www.steptoinstall.com/folder1/index.php

4)www.steptoinstall.com/folder1/folder2

5)www.steptoinstall.com/folder1/folder2/

6)www.steptoinstall.com/folder1/folder2/index.php

7)www.steptoinstall.com/folder1/folder2/index.php?id=12

但我想最後一個文件夾的名稱,如

1)無

2)文件夾1

3)文件夾1

4)文件夾2

5)文件夾2

6)文件夾2

7)文件夾2

我使用以下,但沒有用。

<?php 
    $url = $_SERVER['REQUEST_URI']; 
    print_r(dirname($url)); 
?> 

我怎樣才能在PHP中獲得這個輸出,而不是在.htaccess中?

回答

1
$path = 'www.steptoinstall.com/folder1/folder2/'; 
$folders = explode('/', $path); 
$i = 0; 
foreach($folders as $folder) { 
    if (strpos($folder, '.') !== FALSE || empty($folder)) { 
     unset($folders[$i]); 
    } 
    $i++; 
} 
$what_we_need = end($folders); 
echo $what_we_need; 

對不起,我的第一個答案是waaay關閉,這應該工作proberly。

0

也許這會爲你工作

<?php 
    $urls = array(
     'http://www.steptoinstall.com', 
     'http://www.steptoinstall.com/folder1', 
     'http://www.steptoinstall.com/folder1/folder2/index.php?id=12' 
    ); 

// The Function for your work 
function getFolder($url) { 
    $res = parse_url($url); 
    if(!isset($res['path'])) { 
     return false; 
    } 
    $res = explode('/',$res['path']); 
    $out = false; 
    foreach($res as $p) { 
     if(!empty($p) && strpos($p,'.')===false) $out = $p; 
    } 
    return $out; 
} 

// Testing 
foreach($urls as $url) { 
    var_dump(getFolder($url)); 

} 
0

如果我正確理解你的問題,你可以使用下面的自定義功能

function get_arg() { 
    $arguments = array(); 
    $path = $_SERVER['REQUEST_URI']; 
    if (isset($path)) { 
     $arguments = explode('/', $path); 
    } 
    $url_len = count($arguments); 
    return ($arguments[$url_len - 2]) ? $arguments[$url_len - 2] : 'none'; 
} 

希望這將幫助你。

0

我用正則表達式:

<?php 
$data = array(
'www.steptoinstall.com', 
'www.steptoinstall.com/folder1', 
'www.steptoinstall.com/folder1/index.php', 
'www.steptoinstall.com/folder1/folder2', 
'www.steptoinstall.com/folder1/folder2/', 
'www.steptoinstall.com/folder1/folder2/index.php', 
'www.steptoinstall.com/folder1/folder2/index.php?id=12', 
); 

foreach($data as $url) 
{ 
    print $url." ".get_folder($url)."\n"; 
} 

function get_folder($url) 
{ 
    $url = preg_replace('/(.*)\/.*\..*/', '$1', $url); 
    $url = preg_replace('/\/$/', '$1', $url); 

    $matches = array(); 
    if (preg_match('/.*\/(.*)/', $url, $matches)) 
    { 
     return $matches[1]; 
    } 

    return ''; 
} 

輸出:

www.steptoinstall.com 
www.steptoinstall.com/folder1 folder1 
www.steptoinstall.com/folder1 folder1 
www.steptoinstall.com/folder1/folder2 folder2 
www.steptoinstall.com/folder1/folder2 folder2 
www.steptoinstall.com/folder1/folder2 folder2 
www.steptoinstall.com/folder1/folder2 folder2 

您在這裏有可能出現的問題:很難 「www.steptoinstall.com/folder1」 和「WWW區別開來。 「steptoinstall.com/folder1/index.php」 - 如果有沒有.php結尾的SEF網址。