解析字符串 - 使用正则表达式或类似的东西?
我正在编写路由类并且需要帮助。我需要解析 $controller 变量并将该字符串的一部分分配给另一个变量。这是 $controller 的示例:
$controller = "admin/package/AdminClass::display"
//$path = "admin/package";
//$class = "AdminClass";
//$method = "display";
$controller = "AdminClass::display";
//$path = "";
//$class = "AdminClass";
//$method = "display";
$controller = "display"
//$path = "";
//$class = "";
//$method = "display";
这三种情况就是我所需要的。是的,我可以编写很长的程序来处理这种情况,但我需要的是使用正则表达式和函数 preg_match_all 的简单解决方案
有什么建议吗?
I'm writing routing class and need help. I need to parse $controller variable and assign parts of that string to another variables. Here is examples of $controller:
$controller = "admin/package/AdminClass::display"
//$path = "admin/package";
//$class = "AdminClass";
//$method = "display";
$controller = "AdminClass::display";
//$path = "";
//$class = "AdminClass";
//$method = "display";
$controller = "display"
//$path = "";
//$class = "";
//$method = "display";
This three situations is all i need. Yes, i can write long procedure to handle this situations, but what i need is simple solution with regex, with function preg_match_all
Any suggestion how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下正则表达式应该为您完成此操作,然后您可以将捕获的组保存到
$path
、$class
和$method
。这是红宝石:
http://www.rubular.com/r/1vPIhwPUub
你的 php 代码可能看起来像这样:
The following regex should accomplish this for you, you can then save the captured groups to
$path
,$class
, and$method
.Here is a Rubular:
http://www.rubular.com/r/1vPIhwPUub
Your php code might look something like this:
这假设类内的路径和方法名称只能包含字母。
完整的正则表达式如下:
两个非捕获组:第一个使所有路径和类可选,第二个避免捕获单个路径元素。
说明:
[a-zA-Z]+/
;*
量词应用于上面;但正则表达式不是原子,因此我们需要一个组。由于我们不想捕获单个路径元素,因此我们使用非捕获组:(?:[a-zA-Z]+/)*
;((?:[a-zA-Z]+/)*)
; 上使用捕获组;([a-zA-Z]+)
;((?:[a-zA-Z]+/)*)([a-zA-Z]+)::
;(?:((?:[a-zA-Z]+/)*)([a -zA-Z]+)::)?
;(?:((?:[a-zA-Z]+/)*)([a- zA-Z]+)::)?([a-zA-Z]+)
;^(?:((?:[a-zA-Z]+/ )*)([a-zA-Z]+)::)?([a-zA-Z]+)$
唷。
This supposes that paths within the class, and the method name, can only contain letters.
The full regex is the following:
Two non capturing groups: the first one which makes all the path and class optional, the second which avoids the capture of individual path elements.
Explanation:
[a-zA-Z]+/
;*
quantifier to the above; but the regex is not an atom, we therefore need a group. As we do not want to capture individual path elements, we use a non capturing group:(?:[a-zA-Z]+/)*
;((?:[a-zA-Z]+/)*)
;([a-zA-Z]+)
;((?:[a-zA-Z]+/)*)([a-zA-Z]+)::
;(?:((?:[a-zA-Z]+/)*)([a-zA-Z]+)::)?
;(?:((?:[a-zA-Z]+/)*)([a-zA-Z]+)::)?([a-zA-Z]+)
;^(?:((?:[a-zA-Z]+/)*)([a-zA-Z]+)::)?([a-zA-Z]+)$
Phew.