dpw63348 2012-02-19 21:47
浏览 75
已采纳

PHP preg_match,如何只捕获命名的正则表达式?

So this is the problem, Im using preg_match, to match current URI from browser, with the ones defined in my router.php config file. Im building Router/Dispatcher similar to Django.

What I want is that preg_match() captures only named regexs in $matches variable.

So If I have regexs like this:

^(?<param1>[a-z]+(?:\-[a-z]+)*)\.domain\.com\/[a-z]+(?:\/)?(?<param2>[a-z]+)?\/?$

Rubural link: CLICK

When I compare current URI with this regexs it matches, but $matches variable returns this:

array ( 0 => 'sub.domain.com/page/pageurl/', 'param1' => 'sub', 1 => 'sub', 'param2' => 'pageurl', 2 => 'pageurl', ) 

Is it possible to tell preg_match() to return only named matches, and exclude those numeric one, what I would like to get is Associative Array :)

I could use foreach() and loop through $match and then inside check if its numeric or not... is there any better way?

Thanks

  • 写回答

3条回答 默认 最新

  • dtt2012 2012-02-19 21:57
    关注

    I can't find anything in the PHP manuals about named subpatterns in the first place, but I'm going to take an educated guess and say that you can't prevent the numeric keys in the resulting array.

    The ground for this guess is that key 0 always contains the full match, and there's no way of naming that match.

    If you want to strip out numeric indices, the best way would probably be a foreach loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据