开发者

preg_replace for a specific URL containing parameters

I'm tryi开发者_如何学运维ng 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!


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.


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
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜