2014-09-23 40 views
0

這裏的URI路徑我需要解析:正則表達式爲URI路徑的第一3個部件

大鼓/ SAM /β-類森林%E2%84%A2 /產物的一個

我需要只提取前三個以斜線結尾的組件。

preg_match("/^([\w\/ %\.-]*){3}/", $input_line, $output_array); 

這幾乎得到我想要的,但它不包括'%E2%84%A2'。我一直在重新排列http://www.phpliveregex.com/的東西,但無濟於事。

請注意,如果我嘗試解析完整的URL,說mysite.com/tom-tom/sam/beta-forest%E2%84%A2/product-a,那麼這個正則表達式得到我想要的:

的preg_match(「/^(https?://)?([\da-z.-]+).([az.]{2,6})([/\w %。 - ] *){3} //「,$ path,$ output_array);

我需要解析URI路徑,但我需要包含%符號。嘆氣..

編輯:

我的預期成果是:

tom-tom/sam/beta-forest%E2%84%A2/ 
+0

什麼是你期望的輸出? – 2014-09-23 15:08:15

+1

也許parse_url可能對你有用http://mx1.php.net/manual/es/function.parse-url.php – 2014-09-23 15:08:32

+0

@Alx http://regex101.com/r/rD4sO4/2 – 2014-09-23 15:10:08

回答

0

你必須需要包括啓動模式,以獲得前三個部分。

preg_match("/^(?:[^\/]*\/){3}/", $input_line, $output_array); 

DEMO

+0

你可以避免逃跑通過使用其他分隔符... – hwnd 2014-09-23 15:15:33

+0

是的,但它不是一個問題。 – 2014-09-23 15:17:12

+0

確實,只是醜陋而混亂,但又是用戶的偏好。 – hwnd 2014-09-23 15:17:39

0

如何:

preg_match("~(?:[^/]+/){3}~", $input_line, $output_array);