2015-06-03 251 views
1

我有一個PHP類的URL重寫。我想這個路線網址:preg_match - 這是什麼模式?

- services-paris/ 
- services-paris/8/ 
- services/ 

其計算公式爲:services[ "-" + (city) ]?/[ (0-9) + "/" ]?

的第一件事是[ "-" + (city) ]?,意思是:是可選+必須以「 - 」,但只返回城市。

第二件事是[ (0-9) + "/" ]?,意思是:可選+只有數字+以「/」結尾,但只返回數字。

第二件事是分頁。

最後,我需要這些信息來了解城市和頁面。

那麼..什麼是模式,我是正則表達式的新手。

謝謝!

回答

1

你可以使用這個表達式:

services(?:-([^\/]+))?\/(?:(\d+)\/)?$ 

這會爲您提供包含匹配的表:

  1. 城市名稱(wihtout的 ' - ')
  2. 之後的數字第一個'/'和第二個'/'

請注意,您的城市名稱不能包含任何'/'字符CTER。

Example

+0

它的確定,但也存在一些問題。如果number(page)參數不是數字,並且它是alpha ..它將僅返回第一個參數(如果是isset,則爲城市)。如果isset頁面和頁面不是數字,我不想匹配。例如:request:services-paris/asd/=>將返回city:paris。錯,我不想匹配。 –

+0

只需在最後添加'$'即可。我會更新我的答案。 :) –

0

您可以使用此正則表達式preg_match

'~\bservices(?:-([a-zA-Z. ]+))?(?:/(\d+))?/~' 

RegEx Demo

正則表達式破碎:

\b     # word boundary 
services   # literal text services 
(?:-([a-zA-Z. ]+))? # optional group containing - and a city name 
(?:/(\d+))?   # optional group containing/and a page number 
/     # trailing slash 

PS:城市名稱和頁碼將在拍攝可用組#1和#2。

0

這裏有一個簡單的正則表達式的擊穿

(\w+) # Capture 1 or more letters for 'services' 
(?:-  # Begin non capturing group with '-' 
(\w+) # Capture 1 or more letters for city 
)?  # End non capturing group (optionally matched) 
(?:\/ # Begin non capturing group with '/' 
(\d+) # Capture 1 or more numbers for pagination 
)?  # End non capturing group (optionally matched) 

你可以看到它在行動here

+0

'\ w +'不足以匹配城市名稱。即。 '舊金山'。 – Toto

+1

'([^ \ /] +)'這是我會用的。匹配除'/'字符以外的所有內容。 –

+0

空格將被URL轉義,當然,這將是各種不整潔。無論如何,我希望城市被標準化爲一個詞 - 例如舊金山。 –