把這個域名:使用PHP找到URL的一部分
http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
我如何使用PHP來找到第一和第二斜線之間的一切,無論它是否改變或沒有?
即,老年保健倡導
任何helo將不勝感激。
把這個域名:使用PHP找到URL的一部分
http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
我如何使用PHP來找到第一和第二斜線之間的一切,無論它是否改變或沒有?
即,老年保健倡導
任何helo將不勝感激。
//strip the "http://" part. Note: Doesn't work for HTTPS!
$url = substr("http://www.example.com/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html", 7);
// split the URL in parts
$parts = explode("/", $url);
// The second part (offset 1) is the part we look for
if (count($parts) > 1) {
$segment = $parts[1];
} else {
throw new Exception("Full URLs please!");
}
我認爲Regular Expression
應該沒問題。
嘗試使用例如:/[^/]+/
應該給你/elderly-care-advocacy/
作爲你的例子中數組的第二個索引。
(第一個字符串是/www.?.com/)
Woudld't讓你www.?.co.uk作爲第一場比賽?你要找的是第二場比賽。 – 2009-11-16 13:25:26
我剛剛補充說,但是IIRC php返回一個數組,所以考慮$ arr [1]應該會很好。 – 2009-11-16 13:26:07
了我的頭頂部:
$url = http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
$urlParts = parse_url($url); // An array
$target_string = $urlParts[1] // 'elderly-care-advocacy'
乾杯
此代碼不起作用。 – 2009-11-16 14:33:06
explode('/', $a);
所有你應該這樣做,首先解析url,然後爆炸字符串並獲得第一部分。隨着一些理智的檢查,將樂像以下:
$url = 'http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html';
$url_parts = parse_url($url);
if (isset($url_parts['path'])) {
$path_components = explode('/', $ul_parts['path']);
if (count($path_components) > 1) {
// All is OK. Path's first component is in $path_components[0]
} else {
// Throw an error, since there is no directory specified in path
// Or you could assume, that $path_components[0] is the actual path
}
} else {
// Throw an error, since there is no path component was found
}
$url = "http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html";
$parts = parse_url($url);
$host = $parts['host'];
$path = $parts['path'];
$items = preg_split('/\//',$path,null,PREG_SPLIT_NO_EMPTY);
$firstPart = $items[0];
Parse_URL是您最佳的選擇。它將URL字符串分解爲組件,您可以選擇查詢。
此功能可用於:
function extract_domain($url){
if ($url_parts = parse_url($url), $prefix = 'www.', $suffix = '.co.uk') {
$host = $url_parts['host'];
$host = str_replace($prefix,'',$host);
$host = str_replace($suffix,'',$host);
return $host;
}
return false;
}
$host_component = extract_domain($_SERVER['REQUEST_URI']);
我很驚訝過,但這個工程。
$url='http://www.?.co.uk/elderly-care-advocacy/...'
$result=explode('/',$url)[3];
如果url是https:// *那麼這將返回url的主機部分 – 2009-11-16 13:40:00
感謝您的工作,請多多指教!並感謝其他人爲您的帖子提供幫助。 – Andy 2009-11-16 13:48:19
@彼得:是的,我在評論中這樣說。 – Boldewyn 2009-11-16 15:38:30