我在PHP中有一个字符串,它是一个包含所有参数的URI:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0
Run Code Online (Sandbox Code Playgroud)
我想完全删除一个参数并返回保留字符串.例如,我想删除arg3
并最终:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1
Run Code Online (Sandbox Code Playgroud)
我总是想删除相同的参数(arg3
),它可能是也可能不是最后一个参数.
思考?
编辑:可能有一堆奇怪的角色,arg3
所以我喜欢这样做(实质上)将是:
$newstring = remove $_GET["arg3"] from $string;
Run Code Online (Sandbox Code Playgroud)
这里没有使用正则表达式的真正原因,您可以使用字符串和数组函数.
您可以explode
将?
(您可以使用substr
获取子字符串并strrpos
获取最后一个的位置?
)之后的部分放入数组中,并使用unset
删除arg3
,然后join
将字符串放回到一起:
$string = "http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0";
$pos = strrpos($string, "?"); // get the position of the last ? in the string
$query_string_parts = array();
foreach (explode("&", substr($string, $pos + 1)) as $q)
{
list($key, $val) = explode("=", $q);
if ($key != "arg3")
{
// keep track of the parts that don't have arg3 as the key
$query_string_parts[] = "$key=$val";
}
}
// rebuild the string
$result = substr($string, 0, $pos + 1) . join($query_string_parts);
Run Code Online (Sandbox Code Playgroud)
请参阅http://www.ideone.com/PrO0a上的操作