PHP preg_match,带有可选的数学规则

时间:2014-11-15 06:07:02

标签: php regex preg-match optional-parameters optional

我想解析这个字符串并获取特殊值 要解析的字符串具有其中一种模式

app/(integer)/(integer)/(text or null)
app/(integer)/(text or null)
app/(text or null)

我可以使用preg_match进行简单使用,但我无法编写可选参数

preg_match('%app/(\d+)/(\d+)/(\.*)$%', $text, $matches)

2 个答案:

答案 0 :(得分:1)

您给定的模式会导致您想要匹配的以下情况:

app/1/2/foo
app/1/2/
app/1/bar
app/1/
app/bar
app/

这可以使用带有OR运算符(|)的正则表达式来实现。 语法如下:

~app/(\d+)/(\d+)/(\w+)|app/(\d+)/(\d+)/|app/(\d+)/(\w+)|app/(\d+)/|app/(\w+)|app/$~

我为你的情况建立了一个regex101“小提琴”: http://regex101.com/r/zT9jT6/1

请注意,“app /”将匹配$ matches数组中的0个条目。

etvoilà。

答案 1 :(得分:1)

我做:

$urls = array(
    'app/12/34/text',
    'app/12/34/',
    'app/56/text',
    'app/56/',
    'app/text',
    'app/',
);
foreach ($urls as $url) {
    preg_match( "#app/(?:(\d+)/)?(?:(\d+)/)?(.*)#", $url, $m);
    print_r($m);
}

<强>输出:

Array
(
    [0] => app/12/34/text
    [1] => 12
    [2] => 34
    [3] => text
)
Array
(
    [0] => app/12/34/
    [1] => 12
    [2] => 34
    [3] =>
)
Array
(
    [0] => app/56/text
    [1] => 56
    [2] =>
    [3] => text
)
Array
(
    [0] => app/56/
    [1] => 56
    [2] =>
    [3] =>
)
Array
(
    [0] => app/text
    [1] =>
    [2] =>
    [3] => text
)
Array
(
    [0] => app/
    [1] =>
    [2] =>
    [3] =>
)