正则表达式匹配可选部分

发布于 2024-10-01 05:14:04 字数 330 浏览 3 评论 0原文

例如,我这里有两个可能的字符串。

/user/name

/user/name?redirect=1

试图找出正确的正则表达式来匹配以下结果:

Array ([0] => /user/name [1] => user [2] => name)

我认为我遇到问题的部分是问号和其后的 GET 查询是可选的,并且只会出现其中的一些时间。我尝试了很多不同的方法,但似乎无法想出一个正则表达式来匹配字符串,无论 ?** 是否存在。

So I have two possible strings here for example.

/user/name

and

/user/name?redirect=1

I'm trying to figure out the proper regex to match either with a result of:

Array ([0] => /user/name [1] => user [2] => name)

I think the part I'm having an issue with is that the question mark and the GET query after it are optional and will only be there some of the time. I've tried many different things and can't seem to come up with a regex to match the strings whether the ?** is there or not.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

够运 2024-10-08 05:14:04

不要使用正则表达式,

使用 parse_url()explode()

$result = parse_url("/here/is/a/path?query=string");
$pieces  = explode("/", $result['path']);

Don't use a regex,

Use parse_url(), and explode()

$result = parse_url("/here/is/a/path?query=string");
$pieces  = explode("/", $result['path']);
小…红帽 2024-10-08 05:14:04

? 是“零或一”量词。因此,您可以将 (\?.*)? 附加到正则表达式中,该正则表达式可以选择匹配零个或一个文字问号实例,后跟任意数量的字符。

? is the "zero-or-one" quantifier. So you could append (\?.*)? to your regex, which will optionally match zero or one instances of a literal question-mark followed by any number of characters.

给我一枪 2024-10-08 05:14:04

在正则表达式中,您可以使用 ? 参数将某些内容指定为可选。例如,正则表达式 n?ever 匹配 evernever

在您的情况下,您可能需要类似 /([A-Za-z0-9]+)/([A-Za-z0-9]+)(\?redirect=1)?

这将匹配 /.../... (假设“...”由字母和数字组成)或 /.../...?redirect=1

如果问号后面可能有更多可能的标志,而不仅仅是 redirect=1,请尝试更通用的:

/([A-Za-z0-9]+)/ ([A-Za-z0-9]+)(\?[A-Za-z0-9]+=[A-Za-z0-9]+)?(&[A-Za-z0-9] +=[A-Za-z0-9]+)*

In regex you can specify something as optional using the ? parameter. So for instance, the regex n?ever matches ever and never.

In your case, you might want something like /([A-Za-z0-9]+)/([A-Za-z0-9]+)(\?redirect=1)?

This will match /.../... (given the "..." consist of letters and numbers) or /.../...?redirect=1

If there are more possible flags that could come after the question mark than simply redirect=1, try the more general:

/([A-Za-z0-9]+)/([A-Za-z0-9]+)(\?[A-Za-z0-9]+=[A-Za-z0-9]+)?(&[A-Za-z0-9]+=[A-Za-z0-9]+)*

方觉久 2024-10-08 05:14:04
preg_match('{^/(user)/(name)(?=\?redirect=1)?$}', $subject, $matches);

这是一个前瞻断言。它不会包含在比赛本身中。

但就像其他答案一样,您不应该使用正则表达式来解析 URL。为了完整性,仅发布特定问题的实际答案。

preg_match('{^/(user)/(name)(?=\?redirect=1)?$}', $subject, $matches);

This is a look ahead assertion. It won't be included in the match itself.

But like the other answers suggest you shouldn't use regex to parse URLs. Just posting the actual answer to the specific question for completeness.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文