我用正則表達式:
<?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網址。