preg_match -它的模式是什么?


preg_match - What is the pattern of that?

我有一个php类URL重写。我想路由这些url:

 - services-paris/
 - services-paris/8/
 - services/
公式为:services[ "-" + (city) ]? / [ (0-9) + "/" ]?

第一个是[ "-" + (city) ]?,表示:是可选的+必须以"-"开头,但只返回城市。

第二件事是[ (0-9) + "/" ]?,意思是:是可选的+只数字+以"/"结尾但只返回数字。

第二件事是分页。

最后我需要这些信息来了解城市和页面。

. .什么是模式,我是一个新手在正则表达式。

谢谢!

你可以使用这个正则表达式:

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

它会给你一个匹配表其中包含:

  1. 城市名称(不带'-')
  2. 第一个'/'之后第二个'/'之前的数字

注意你的城市名不能包含任何'/'字符。

示例

您可以对preg_match使用此正则表达式:

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

RegEx演示

RegEx分手:

'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中可用。

下面是一个带有分解的简单正则表达式

('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)

你可以在这里看到它的作用