2012-02-09 115 views
0

我不擅長做preg_match()。有人可以幫我創建一個preg_match()來檢索url中的最後一個參數。如何對此字符串執行preg_match()?

PHP代碼:

$url = "http://my.example.com/getThis"; 
$patern = ""; //need to create this 

$result = preg_match($pattern, $url, $matches); 

謝謝!

回答

1

穆罕默德·阿布拉Istiadi和AD7six的答案是更好的方法來完成這項工作比這一點,我強烈建議使用爆炸,

但是,爲了回答你的問題:

$url = "http://my.example.com/getThis"; 
$pattern = "/\/([^\/]*)$/"; 
preg_match($pattern, $url, $matches); 
print_r($matches);` 
3

檢索最後一個參數?另一種方法是使用preg_match,將$url拆分爲/字符,然後獲取最後一個元素。

$url = "http://my.example.com/getThis"; 
$arr = explode("/", $url); 

$result = $arr[count($arr) - 1]; 

$result將具有值getThis

+2

+ 1 for avoi丁慢的正則表達式! – Zenexer 2012-02-09 15:54:40

+2

如果您要使用爆炸 – AD7six 2012-02-09 15:55:28

1

不要使用正則表達式時,他們沒有必要的(特別是如果他們是不是你的長處)

所有你需要的是:

$lastSlash = strrpos($url, '/'); 
$result = substr($url, $lastSlash + 1); 
0

有一個簡單的PHP函數parse_url()來處理這個問題。

這裏有3種不同的方法,最後,使用parse_url()函數是最簡單的。第一個是簡單的正則表達式。

第二個是相同的正則表達式,但爲結果數組添加鍵名稱。

第三種方法是使用PHP的parse_url()函數,它可以更簡單地返回所有信息,但確實會捕獲路徑的「/」。 [路徑] => /獲得OS 3.0

代碼:

echo "Attempt 1:\n\n"; 
$url = "http://my.example.com/getThis"; 
$pattern = "/(.*?):\/\/(.*?)\/(.*)/"; //need to create this 
$result = preg_match($pattern, $url, $matches); 
print_r($matches); 

echo "\n\nAttempt 2:\n\n"; 
$url = "http://my.example.com/getThis"; 
$pattern = "/(?<scheme>.*?):\/\/(?<host>.*?)\/(?<path>.*)/"; //need to create this 
$result = preg_match($pattern, $url, $matches); 
print_r($matches); 

echo "\n\nAttempt 3:\n\n"; 
$better = parse_url($url); 
print_r($better); 

結果:

嘗試1:

Array 
(
    [0] => http://my.example.com/getThis 
    [1] => http 
    [2] => my.example.com 
    [3] => getThis 
) 


Attempt 2: 

Array 
(
    [0] => http://my.example.com/getThis 
    [scheme] => http 
    [1] => http 
    [host] => my.example.com 
    [2] => my.example.com 
    [path] => getThis 
    [3] => getThis 
) 


Attempt 3: 

Array 
(
    [scheme] => http 
    [host] => my.example.com 
    [path] => /getThis 
) 

希望它能幫助^^

+0

,則只需使用'$ result = end($ arr)',所有上述示例都依賴於不包含/的工作路徑,例如,以上代碼示例都不會爲「http://my.example.com/foo/getThis」返回「getThis」。由於這個問題的措辭不明確,因爲這個問題實際上是所期望的行爲 – AD7six 2012-02-09 16:51:46

+0

@ AD7six - 的確,我確實考慮過這一點,通常我不需要完整路徑,我假設如果s /他需要更多的時間來回答我。除此之外,我可以根據同一個問題回答100個不同的答案。 >!h 我的腳本1和2也假設總會有一個路徑,或者至少在域後面有一個'/'。 – GravyCode 2012-02-09 18:23:46