views:

245

answers:

2

http://www.chuckecheese.com/rotator.php?cheese=4&id=1

I want to take out the id, leaving the cheese to stand alone. I tried:

$qs = preg_replace("[^&id=*]" ,'',$_SERVER[QUERY_STRING]);

But that said I was using an improper modifier. I want to remove "$id=" and whatever number comes after it. Are regexp really as hard as they seem for me?

+2  A: 

You're getting an improper modifier because you need to surround your expression with an arbitrary delimeter. I tend to use ! because I rarely want to look for that but /, ~ and others are common. So:

$qs = preg_replace('!&id=.*!', '', $_SERVER['QUERY_STRING']);

The other way to do this is using parse_url(). For example:

$s = 'http://www.chuckecheese.com/rotator.php?cheese=4&id=1';
$url = parse_url($s);
parse_str($url['query'], $qs);
unset($qs['id']);
$url['query'] = http_build_str($qs);
$out = http_build_url($url);
echo $out;

Note: this requires the pecl_http extension, which you have to compile yourself on Windows it seems.

cletus
A: 

If the ID really can be anything, try this:

$qs = preg_replace("/(&|?)id=[^&]+/", '', $_SERVER[QUERY_STRING]);

If the ID is definitely a number, this one should do the trick:

$qs = preg_replace("/(&|?)id=\d+/", '', $_SERVER[QUERY_STRING]);
bobthecow