preg_match - 那是什么模式?
preg_match - What is the pattern of that?
我有一个 php class 用于 URL 重写。我想路由此网址:
- services-paris/
- services-paris/8/
- services/
公式为:services[ "-" + (city) ]? / [ (0-9) + "/" ]?
首先是[ "-" + (city) ]?
,意思是:是可选的+必须以“-”开头,但是到return只有城市。
第二件事是[ (0-9) + "/" ]?
,意思是:是可选的+只有数字+以“/”结尾但return只有数字。
第二个是分页。
最后我需要这些信息来了解城市和页面。
所以..模式是什么,我是正则表达式的新手。
谢谢!
您可以将此正则表达式用于 preg_match
:
'~\bservices(?:-([a-zA-Z. ]+))?(?:/(\d+))?/~'
正则表达式分解:
\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 中可用。
您可以使用这个正则表达式:
services(?:-([^\/]+))?\/(?:(\d+)\/)?$
它将为您提供 table 个匹配项,其中包含:
- 城市名称(不含“-”)
- 第一个'/'之后和第二个'/'之前的数字
请注意,您的城市名称不得包含任何“/”字符。
这是一个带有细分的简单正则表达式
(\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
我有一个 php class 用于 URL 重写。我想路由此网址:
- services-paris/
- services-paris/8/
- services/
公式为:services[ "-" + (city) ]? / [ (0-9) + "/" ]?
首先是[ "-" + (city) ]?
,意思是:是可选的+必须以“-”开头,但是到return只有城市。
第二件事是[ (0-9) + "/" ]?
,意思是:是可选的+只有数字+以“/”结尾但return只有数字。
第二个是分页。
最后我需要这些信息来了解城市和页面。
所以..模式是什么,我是正则表达式的新手。
谢谢!
您可以将此正则表达式用于 preg_match
:
'~\bservices(?:-([a-zA-Z. ]+))?(?:/(\d+))?/~'
正则表达式分解:
\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 中可用。
您可以使用这个正则表达式:
services(?:-([^\/]+))?\/(?:(\d+)\/)?$
它将为您提供 table 个匹配项,其中包含:
- 城市名称(不含“-”)
- 第一个'/'之后和第二个'/'之前的数字
请注意,您的城市名称不得包含任何“/”字符。
这是一个带有细分的简单正则表达式
(\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