模式匹配后 URL 路径的剩余部分到结果数组
Remainder of URL path to results array after pattern match
我很难让我的正则表达式做我想让它做的事:(
我想让我的正则表达式做以下两件事:
- 找到 "brand" 或 "profile"
模式匹配后的下一个 URL 路径部分的 ID
- 比将 ID 后的 URL 路径部分的其余部分拆分为匹配数组中的单独项,ID 后的 URL 路径部分的数量可能不同于 none到多个并且尾部斜杠并不总是存在
我设法让第一部分通过:
<?php
$url = 'https://demo.com/show/profile/123/slug/etc/';
$pattern = '/\/(brand|profile)?\/([\d]+)/';
preg_match($pattern, $url, $matches);
var_dump($matches);
适用于所有这些测试字符串:
https://demo.com/show/profile/123
https://demo.com/show/profile/123/
https://demo.com/show/profile/123/slug
https://demo.com/show/profile/123/slug/
https://demo.com/show/profile/123/slug/etc
https://demo.com/show/profile/123/slug/etc/
但我似乎无法解决第二部分,即使在搜索了几天的解决方案之后也是如此。到目前为止,我最 "successful" 的尝试是:
\/(brand|profile)?\/([\d]+)\/?(.*)?\/?
该模式捕获 URL 路径的其余部分,包括尾部斜线(顺便说一句 - 我不想要尾部斜线)。
我在以下位置提供了第一部分的代码:phpliveregex.com/p/pMO
谁能帮我用第二部分的代码扩展它?
非常感谢!
我建议把这个问题分成两个子问题。
我是说。
我们可以用这个正则表达式
做第一个 preg_match
(brand|profile)\/(\d+)(.*)
这里有
- 第1夺冠组全场比赛。
- 在第二个捕获组中,您的标签(品牌或个人资料)
- 在第 3 个捕获组中我们有 ID(编号)
- 并且在第 4 个捕获组中 URL 提醒
然后有了完整的 URL 提醒(第 4 个捕获组),我们可以用这个正则表达式
做一个 preg_match_all
[^\/]+
这里有所有提醒路径。
我很难让我的正则表达式做我想让它做的事:(
我想让我的正则表达式做以下两件事:
- 找到 "brand" 或 "profile" 模式匹配后的下一个 URL 路径部分的 ID
- 比将 ID 后的 URL 路径部分的其余部分拆分为匹配数组中的单独项,ID 后的 URL 路径部分的数量可能不同于 none到多个并且尾部斜杠并不总是存在
我设法让第一部分通过:
<?php
$url = 'https://demo.com/show/profile/123/slug/etc/';
$pattern = '/\/(brand|profile)?\/([\d]+)/';
preg_match($pattern, $url, $matches);
var_dump($matches);
适用于所有这些测试字符串:
https://demo.com/show/profile/123
https://demo.com/show/profile/123/
https://demo.com/show/profile/123/slug
https://demo.com/show/profile/123/slug/
https://demo.com/show/profile/123/slug/etc
https://demo.com/show/profile/123/slug/etc/
但我似乎无法解决第二部分,即使在搜索了几天的解决方案之后也是如此。到目前为止,我最 "successful" 的尝试是:
\/(brand|profile)?\/([\d]+)\/?(.*)?\/?
该模式捕获 URL 路径的其余部分,包括尾部斜线(顺便说一句 - 我不想要尾部斜线)。
我在以下位置提供了第一部分的代码:phpliveregex.com/p/pMO
谁能帮我用第二部分的代码扩展它?
非常感谢!
我建议把这个问题分成两个子问题。
我是说。
我们可以用这个正则表达式
做第一个preg_match
(brand|profile)\/(\d+)(.*)
这里有
- 第1夺冠组全场比赛。
- 在第二个捕获组中,您的标签(品牌或个人资料)
- 在第 3 个捕获组中我们有 ID(编号)
- 并且在第 4 个捕获组中 URL 提醒
然后有了完整的 URL 提醒(第 4 个捕获组),我们可以用这个正则表达式
做一个preg_match_all
[^\/]+
这里有所有提醒路径。