dongzhi6382 2017-11-23 12:13
浏览 38

用preg_match解析url - 正则表达式

I've trying to make my own route class - and I've hot problem with parsing valid url's.

This is an example url: http://localhost/app/module/command/i15

And I need every element after slash / to be an additional element in array creating using preg_match in php.

So - for searching of numbers I've got: ([0-9]+) Searching strings that contains letters, signs like - or _ I've got ([^.]+) (here's the problem)

whole regexp looks like this:

(app)\/(module)\/([^.]+)\/i([0-9]+)

i want an array of 5 elements, something like that:

0 => app, 1=> module, 2 => command, 3 => i15

It will be more beauty if preg_match will return only something like that:

0 => app, 1=> module, 2 => command, 3 => 15 (without I as param identifier)

Can anyone quick help me with this ? I stuck 2 days in that, and can't find right solution.

EDIT: I've got some regexp predefined like:

/app/contacts/list => (app)\/(contacts)\/([^.]+)
/app/contacts/edit/i15 => (app)\/(contacts)\/([^.]+)\/i([\d]+)
/app/contacts/view/i15-c2 => (app)\/(contacts)\/([^.]+)\/i([\d]+)-c([\d]+)

And for all of those I prepare different regexp like above. Problem stars when I need to parse something between:

/app/contacts/preview/random-name/i15-c2 

or

/app/contacts/preview/random-name-i15-c2

([^.]+) catches also \ (slash) - and in above first example this slash broke whole regexp :-(

EDIT SECOND TIME :-)

I've got some predefined regexps for some paths. Lets have a look:

$regexp = [
    [0 => '(app)\/([^/]+)'],
    [1 => '(app)\/([^/]+)\/i([0-9]+)']
];

Next i check current url and match the best result - I know what I want, but php doesn't know what user select so:

if I enter url with path:

app/username/i15

System shows me that $regexp[0] is best result - what it is not true, because $regexp[1] are the best.

I hope this explains my problem.

  • 写回答

2条回答 默认 最新

  • douyue7408 2017-11-23 12:22
    关注

    Since you're using groups to capture in your regex, you can use them to create your desired array. Pass a variable to preg_match() to store the groups:

    $components = [];
    preg_match('#(app)/(module)/([^.]+)/i([0-9]+)#', $uri, $components);
    

    Now the first element of $components is the whole match, and then the groups.

    array_shift($components); # discard first element
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题