我有一個網站,我需要使用PHP獲取一個網頁的URL。網址可能是東西www.mydomain.com/thestringineed/
,也可以www.mydomain.com/thestringineed?data=1
也可以是www.mydomain.com/ss/thestringineed
使用PHP獲取URL的一部分
所以它總是最後一個字符串,但我不想以後得到什麼?
我有一個網站,我需要使用PHP獲取一個網頁的URL。網址可能是東西www.mydomain.com/thestringineed/
,也可以www.mydomain.com/thestringineed?data=1
也可以是www.mydomain.com/ss/thestringineed
使用PHP獲取URL的一部分
所以它總是最後一個字符串,但我不想以後得到什麼?
收到您將使用parse_url功能,再看看返回的路徑部分。 這樣的:
$url='www.mydomain.com/thestringineed?data=1';
$components=parse_url($url);
//$mystring= end(explode('/',$components['path']));
// I realized after this answer had sat here for about 3 years that there was
//a mistake in the above line
// It would only give the last directory, so if there were extra directories in the path, it would fail. Here's the solution:
$mystring=str_replace(reset(explode('/',$components['path'])),'',$components['path']); //This is to remove the domain from the beginning of the path.
// In my testing, I found that if the scheme (http://, https://, ...) is present, the path does not include
//the domain. (it's available on it's own as ['host']) In that case it's just
// $mystring=$components['path']);
我不得不測試它,但如果它以斜槓結尾,則可能必須'rtrim($ components ['path'],'/') '。在這種情況下,我發佈的答案可能會返回空字符串。 – TecBrat
我認爲這是有效的,至少經過快速測試。謝謝 – user1069269
parse_url
應該會幫助你。
<?php
$url = "http://www.mydomain.com/thestringineed/";
$parts = parse_url($url);
print_r($parts);
?>
這不是OP想要的。在'/ ss/thestringineed'的情況下,它將返回整個事物,而不僅僅是路徑部分中的'thestringineed'。 –
parse_url()
是您正在查找的功能。你想確切的部分,可以通過PHP_URL_PATH
$url = 'http://php.net/manual/en/function.parse-url.php';
echo parse_url($url, PHP_URL_PATH);
使用$_SERVER['REQUEST_URI']
將返回完整當前頁面的URL,你可以用「/」分開,並利用最後的數組索引。這將是最後一個字符串
您可以使用:
$strings = explode("/", $urlstring);
將在URL中刪除所有的「/」並返回一個包含所有單詞的數組。
$strings[count($strings)-1]
現在有你需要的字符串值,但它可能包含,所以我們需要刪除「數據= 1?」:
$strings2 = explode("?", $strings[count($strings)-1]);
$strings2[0]
擁有你是想出來的字符串網址。
希望這有助於!
<?php
$url = 'http://username:[email protected]/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
和你出來說就是
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
/path
我不明白,你想獲得'www.mydomain.com'或'thestringineed /'? – Mediator
爲了澄清,從'/ ss/thestringineed'你只需要'thestringineed'吧? –
Yesstringineed是我唯一需要的部分。 – user1069269