preg_match_all与命名子模式

时间:2015-03-23 10:14:21

标签: php preg-match-all

我无法弄清楚以下表达式:

preg_match_all('/[(?P<slug>\w+\-)\-(?P<flag>(m|t))\-(?P<id>\d+)]+/', $slugs, $matches);

我的$ slugs变量是这样的:

article-slug-one-m-111617/article-slug-two-t-111611/article-slug-three-t-111581/article-slug-four-m-111609/

1 个答案:

答案 0 :(得分:1)

您的表达式似乎是尝试将路径元素拆分为slug,flag和id部分。它失败,因为括号[ ... ]用于匹配字符,但在这里似乎用于将事物保持在一起,如括号。它也无法使slug部分正确,因为它不允许多个单词\w和短-字符系列。即那部分匹配&#39;文章 - &#39;但不是&#39; article-slug-one - &#39;。

也许这就是你想要的?

$slugs = 'article-slug-one-m-111617/article-slug-two-t-111611/article-slug-three-t-111581/article-slug-four-m-111609/';

preg_match_all('/(?P<slug>[\w-]+)\-(?P<flag>[mt])\-(?P<id>\d+)/', $slugs, $matches);

echo "First slug : " . $matches['slug'][0], PHP_EOL;
echo "Second flag: " . $matches['flag'][1], PHP_EOL;
echo "Third ID   : " . $matches['id'][2], PHP_EOL;
print_r($matches);

输出:

First slug : article-slug-one
Second flag: t
Third ID   : 111581

Array
(
    [0] => Array
        (
            [0] => article-slug-one-m-111617
            [1] => article-slug-two-t-111611
            [2] => article-slug-three-t-111581
            [3] => article-slug-four-m-111609
        )

    [slug] => Array
        (
            [0] => article-slug-one
            [1] => article-slug-two
            [2] => article-slug-three
            [3] => article-slug-four
        )

    [1] => Array
        (
            [0] => article-slug-one
            [1] => article-slug-two
            [2] => article-slug-three
            [3] => article-slug-four
        )

    [flag] => Array
        (
            [0] => m
            [1] => t
            [2] => t
            [3] => m
        )

    [2] => Array
        (
            [0] => m
            [1] => t
            [2] => t
            [3] => m
        )

    [id] => Array
        (
            [0] => 111617
            [1] => 111611
            [2] => 111581
            [3] => 111609
        )

    [3] => Array
        (
            [0] => 111617
            [1] => 111611
            [2] => 111581
            [3] => 111609
        )

)