如何从正则表达式获取(部分)变量?
我不太了解正则表达式,我对从正则表达式检查中获取部分变量的可能性有疑问。我尝试解释我在寻找什么...
我有这样的路径:
example.com/dir1/
example.com/dir1/val1
example.com/dir1/val1-val2
我想创建一个提取 dir1 val1 和 val2 的表达式。
我的问题是:
我可以只提取存在的变量还是必须编写 3 个表达式?我的意思是...
如果我使用规则: example.com/dir1/val1-val2
如果我传递如下网址,我只能得到 dir1: www.example.com/category
(dir1 = 类别)?
那么如果网址是:www.example.com/category/car
获取dir1 =category
和val1 = car
I don't know regular expressions so well, I have a doubt regarding the possibility to get partials variables from a regex check. I try to explain what I am looking for...
I have those kind of paths:
example.com/dir1/
example.com/dir1/val1
example.com/dir1/val1-val2
I would like to create an expression that extracts dir1 val1 and val2.
My questions is:
Can I extract only the variables that exists or do I have to write 3 expressions? I mean...
If I put a rule to use: example.com/dir1/val1-val2
Can I only get dir1 if I pass url like: www.example.com/category
(dir1 = category) ?
then If the url was: www.example.com/category/car
get dir1 = category
and val1 = car
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可能的话,
explode("/", $url)
是最简单的。如果结构比允许的更复杂,您可以使用 preg_split() 代替并列出可用作细分符的所有可能字符。explode("/", $url)
is easiest if possible. If the structure is more complex than that allows for, you could use preg_split() instead and list all the possible characters that can be used as subdividers.你可以使用explode('/', $url);要获取包含所有值的数组,不应该使用正则表达式来解决这样的问题
You could use explode('/', $url); to get an array with all your values, regular expressions shouldn't be used to solve problems like this