preg_replace 用于包含参数的特定 URL

发布于 2024-12-05 19:51:58 字数 579 浏览 0 评论 0原文

我正在尝试替换 URL 列表的会话 ID #

例如: http://www.yes.com/index.php?session=e4bce57bc39f67bebde0284f4c2ed9ba&id=1234

我正在尝试摆脱 session=e4bce57bc39f67bebde0284f4c2ed9ba位并保留http://www.yes.com/index.php?id=1234 位。

我正在尝试使用:

preg_replace('&\bhttp://www\.yes\.com/(?:index\.php(?:\?id(?:=[]\d!"#$%\'()*+,./:;<=>?@[\\\\_`a-z{|}~^-]*+)?&i', $subject, $regs)) 

但这不起作用。任何帮助将不胜感激。 谢谢!

I'm trying to replace the session ID # of a list of URLS

Ex: http://www.yes.com/index.php?session=e4bce57bc39f67bebde0284f4c2ed9ba&id=1234

I'm trying to get rid of the session=e4bce57bc39f67bebde0284f4c2ed9ba bit and just keep the http://www.yes.com/index.php?id=1234 bit.

I'm attempting to use:

preg_replace('&\bhttp://www\.yes\.com/(?:index\.php(?:\?id(?:=[]\d!"#$%\'()*+,./:;<=>?@[\\\\_`a-z{|}~^-]*+)?&i', $subject, $regs)) 

But it isn't work. Any help would be appreciated.
Thanks!

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

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

发布评论

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

评论(2

じее 2024-12-12 19:51:58

如果您只想删除 &session=... 部分,那么 preg_replace 可能是最好的选择。只查找该部分而不断言 URL 结构也是有意义的:

$url = preg_replace("/([?&])session=\w+(&|$)/", "$1", $url);

此模式看起来它要么由两个 & 包围,和/或以 ? 和/或 是字符串中的最后一个内容。 \w+ 足以匹配会话 ID 字符串。

If you just want to strip out the &session=... part then preg_replace might be the best option. It also makes sense to look just for that part then and not to assert the URL structure:

$url = preg_replace("/([?&])session=\w+(&|$)/", "$1", $url);

This pattern looks that it's either enclosed by two &, and/or begins with an ? and/or is the last thing in the string. \w+ is sufficient to match the session id string.

谈下烟灰 2024-12-12 19:51:58

比正则表达式稍微冗长一些,但是您可以使用 PHP 自己的 url 处理函数来完成此操作,parse_urlparse_strhttp_build_urlhttp_build_query

// Parse the url to constituent parts
$url_parts = parse_url($_REQUEST);

// Parse query string to $params array
parse_str($url_parts['query'], $params);

// Get rid of the session param
unset($params['session']);

// Rebuild query part of the url without the session val
$url_parts['query'] = http_build_query($params);

// Rebuild the url using http_build_url
$cleaned_url = http_build_url(
    "http://www.example.com"
    , $url_parts
);

Slightly more verbose than a regex, but you can do this using PHP's own functions for url handling, parse_url, parse_str, http_build_url and http_build_query.

// Parse the url to constituent parts
$url_parts = parse_url($_REQUEST);

// Parse query string to $params array
parse_str($url_parts['query'], $params);

// Get rid of the session param
unset($params['session']);

// Rebuild query part of the url without the session val
$url_parts['query'] = http_build_query($params);

// Rebuild the url using http_build_url
$cleaned_url = http_build_url(
    "http://www.example.com"
    , $url_parts
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文