dqf2015 2017-07-14 14:14
浏览 36
已采纳

PHP正则表达式preg_match在url中分隔变量

I have string

$string = 'foo/{id}/bar/{name}';

and I am trying to do regex filtering

wanted output:

$matches = [
  0 => 'foo/{id}/bar/{name}',
  1 => 'id',
  2 => 'name'
]

I got so far: (regex is my weakness)

preg_match('~^' . $magic . '$~', $string, $matches)

edit: there are *n number of {variable} in url

  • 写回答

3条回答 默认 最新

  • duanbi7247 2017-07-14 14:17
    关注

    Use the following preg_match_all approach:

    $str = 'foo/{id}/bar/{name}/many/{number}/of/{variables}';
    preg_match_all('/\{([^{}]+)\}/', $str, $m);
    
    print_r($m[1]);
    

    The output:

    Array
    (
        [0] => id
        [1] => name
        [2] => number
        [3] => variables
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?