用php剥离查询字符串(preg_replace)

时间:2021-06-16 08:45:16

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

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?

但这说明我使用了一个不正确的修饰词。我想删除“$id=”和后面的数字。regexp真的像它们对我来说那么难吗?

2 个解决方案

#1


3  

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:

你得到了一个不合适的修饰符,因为你需要用一个任意的delimeter来包围你的表达式。我喜欢用!因为我很少想去寻找,但是/,~和其他人是很常见的。所以:

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

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

另一种方法是使用parse_url()。例如:

$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.

注意:这需要pecl_http扩展,您必须在Windows上编译自己。

#2


1  

If the ID really can be anything, try this:

如果ID真的可以是任何东西,试试这个:

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

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

如果ID绝对是一个数字,这个应该可以做到:

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

#1


3  

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:

你得到了一个不合适的修饰符,因为你需要用一个任意的delimeter来包围你的表达式。我喜欢用!因为我很少想去寻找,但是/,~和其他人是很常见的。所以:

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

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

另一种方法是使用parse_url()。例如:

$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.

注意:这需要pecl_http扩展,您必须在Windows上编译自己。

#2


1  

If the ID really can be anything, try this:

如果ID真的可以是任何东西,试试这个:

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

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

如果ID绝对是一个数字,这个应该可以做到:

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