【问题标题】:PHP preg_match with optional math rulesPHP preg_match 与可选数学规则
【发布时间】:2014-11-15 06:07:02
【问题描述】:

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

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

我可以使用preg_match 进行简单的使用,但我不能编写可选参数

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

【问题讨论】:

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


    【解决方案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] =>
    )
    

    【讨论】:

      【解决方案2】:

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

      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 个条目。

      等等。

      【讨论】:

        猜你喜欢
        • 2015-02-16
        • 2019-11-20
        • 1970-01-01
        • 1970-01-01
        • 2021-09-01
        • 1970-01-01
        • 2011-07-11
        • 1970-01-01
        • 2012-09-01
        相关资源
        最近更新 更多