preg_match - 那是什么模式?

时间:2015-06-03 09:07:25

标签: php regex preg-match

我有一个用于URL重写的php类。我想路由这个网址:

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

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

首先是[ "-" + (city) ]?,意思是:是可选的+必须以“ - ”开头,但只返回城市。

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

第二件事是分页。

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

那么..模式是什么,我是正则表达式的新手。

谢谢!

3 个答案:

答案 0 :(得分:1)

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

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

它会给你一张包含以下内容的匹配表:

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

    请注意,您的城市名称不得包含任何' /'字符。

    Example

答案 1 :(得分:0)

您可以将此正则表达式用于CAShapeLayer

preg_match

RegEx Demo

RegEx分手:

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

PS:城市名称和页码将分别在捕获的组#1和#2中提供。

答案 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

中看到它
相关问题