使用正则表达式从 URL 获取字符串?

发布于 2024-11-17 15:33:05 字数 451 浏览 2 评论 0原文

正则表达式是我的最爱,任何人都可以帮助我从 URL 中分离出字符串吗?

我想从 URL 获取页面名称,该 URL 可以从输入表单中以以下任何方式出现:

https://www.facebook.com/PAGENAME?sk=wall&filter=2
http://www.facebook.com/PAGENAME?sk=wall&filter=2
www.facebook.com/PAGENAME
facebook.com/PAGENAME?sk=wall

...等等。

我似乎找不到一种方法来隔离 .com/ 之后但 ? 之前的字符串(如果存在的话)。是preg_match、replace还是split?

如果有人可以推荐一个他们认为有用的特别清晰和介绍性的正则表达式指南,我们将不胜感激。

Regex is my bete noire, can anyone help me isolate a string from a URL?

I want to get the page name from a URL which could appear in any of the following ways from an input form:

https://www.facebook.com/PAGENAME?sk=wall&filter=2
http://www.facebook.com/PAGENAME?sk=wall&filter=2
www.facebook.com/PAGENAME
facebook.com/PAGENAME?sk=wall

... and so on.

I can't seem to find a way to isolate the string after .com/ but before ? (if present at all). Is it preg_match, replace or split?

If anyone can recommend a particularly clear and introductory regex guide they found useful, it'd be appreciated.

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

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

发布评论

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

评论(4

亣腦蒛氧 2024-11-24 15:33:05

您可以使用 parse_url 函数,然后从url 的路径:

$parts=parse_url($url);
$path_parts=explode("/", $parts["path"]);
$page=$path_parts[count($path_parts)-1];

You can use the parse_url function and then get the last segment from the path of the url:

$parts=parse_url($url);
$path_parts=explode("/", $parts["path"]);
$page=$path_parts[count($path_parts)-1];
双马尾 2024-11-24 15:33:05

对于学习和测试正则表达式,我发现在线工具 RegExr 非常有用:http://gskinner.com/RegExr/

但正如其他人提到的,在这种情况下,使用适当的函数解析 url 可能会更好。

For learning and testing regexes I found RegExr, an online tool, very useful: http://gskinner.com/RegExr/

But as others mentioned, parsing the url with appropriate functions might be better in this case.

多孤肩上扛 2024-11-24 15:33:05

我认为你可以直接使用这个 php 函数 (parse_url) 而不是使用正则表达式。

I think you can use this php function (parse_url) directly instead of using regex.

使用类似:

substr(parse_url('https://www.facebook.com/PAGENAME?sk=wall&filter=2', PHP_URL_PATH), 1);

Use smth like:

substr(parse_url('https://www.facebook.com/PAGENAME?sk=wall&filter=2', PHP_URL_PATH), 1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文