2010-10-13 33 views
0

我正在用几种语言构建一个应用程序。如何在正则表达式中做到这一点?

test.com/ -english index 
test.com/ca - canadian english index 
test.com/canada-promo - english version of canada promo page 
test.com/ca/canada-promo - canadian english version of promo page 

我该如何过滤?

对不起。实际上有4种语言(/ fr /和/ es /)。我希望能够从传递的URL中确定语言。

+6

不要打扰,我们看英文就好了。 – 2010-10-13 18:37:28

+0

改为使用'split'。 – BrunoLM 2010-10-13 18:38:53

+0

我不明白你的问题是什么。你想用正则表达式匹配什么? – 2010-10-13 18:39:14

回答

2

test.com/(?:([a-z]{2})(?=$|/))?(?:/)?(.*)

说明:

test.com/ #match beginning boilerplate, replace with "^" if need be 
(?:([a-z]{2})(?=$|/))? #match two characters if followed by the end of line or slash 
(?:/)? #consume the slash if there was one 
(.*) #the page 

编辑:好吧,我想这样的作品了。尽管如此,可能会有更优雅的解决方案。第一组是语言代码,第二组是页面。它适用于您提供的四个输入。

1
preg_match('^/((ca|fr|es)(/|$))?(.*)$', $url, $matches); 
$lang = $matches[2]; 
if (!$lang) { 
    $lang = 'en'; 
} 
$url = $matches[4]; 
+0

哎呦,看起来像你修好你的修为我;像我的你最初失败的时候,语言没有跟着斜线。我更喜欢你的;更容易不使用积极的lookahead,只是匹配+消耗斜线。 – 2010-10-13 19:03:57