2014-09-23 63 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);