从查询字符串中删除某个变量
如何从查询字符串中删除某个变量?假设我有一个查询字符串,
$query_string = "first=val1&second=val2&third=val3";
function removevar($var, $query_string) {
return preg_replace("/(".$var."=[^&]*(&))/i","",$query_string);
}
echo removevar("first",$query_string); // ok
echo removevar("second",$query_string); // ok
echo removevar("third",$query_string); // doesn't change the string because third doesn't have a trailing &
如何解决这个问题,以便以可靠的方式从查询字符串中删除变量?可能有人已经有一个函数可以在更复杂的字符串中处理特殊情况来执行此操作。
所以我必须匹配 &
或字符串结尾 ($
),但我不知道如何将其转换为正则表达式。
How do I remove a certain variable from a query string? Say I have a query string
$query_string = "first=val1&second=val2&third=val3";
function removevar($var, $query_string) {
return preg_replace("/(".$var."=[^&]*(&))/i","",$query_string);
}
echo removevar("first",$query_string); // ok
echo removevar("second",$query_string); // ok
echo removevar("third",$query_string); // doesn't change the string because third doesn't have a trailing &
How can this be fixed so that it removes variables from a query string in a robust way? Probably someone already has a function that does this along with special cases in more complex strings.
So I'd have to match either &
or end of the string ($
) but I don't know how to turn that into regex.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这应该可以解决问题。
This should do the trick.
为此,您不一定需要正则表达式,因为 PHP 确实具有可以解析和构建查询字符串的函数 (
parse_str
和
http_build_query
分别):请注意,您需要解码使用这些函数之前先参考 HTML 字符。
You don’t necessarily need regular expressions for this as PHP does have functions that can parse and build query strings (
parse_str
andhttp_build_query
respectively):Note that you need to decode the HTML character references before using these functions.
您可能会更幸运地使用:
html_entity_decode
来获得“正常”查询字符串。parse_str
将查询字符串放入数组中。取消设置
该数组中所需的键。http_build_query
重建字符串。htmlspecialchars
以将&
返回到&
。不如正则表达式路由简洁,但更不容易出错。
You will probably have more luck using:
html_entity_decode
to get the 'normal' query-string.parse_str
to get the query string into an array.unset
the desired key in that array.http_build_query
to rebuild the string.htmlspecialchars
on it to get the&
back to&
.Less concise than the regex route, but a lot less error-prone.
通常,对于像这样涉及查询字符串的代码,最好始终使用内置的 PHP 函数,而不是正则表达式语法/公式。这就是我所做的,代码的主要部分包括以下 PHP 内置函数:-
parse_str
函数in_array
函数http_build_query
功能希望有帮助。
Normally for codes like this, which involves a query string, it is always best to go for the in-built PHP functions rather than for the regex syntax / formula. That is what I've done, and the main parts of the code include the following PHP in-built functions:-
parse_str
Functionin_array
Functionhttp_build_query
FunctionHope it helps.
有些函数可以直接处理查询字符串。
There are functions, that can handle query strings directly.