繁体   English   中英

在php中删除一部分URL参数字符串

[英]remove a part of a URL argument string in php

我在PHP中有一个字符串,它是带有所有参数的URI:

$string = http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0

我想完全删除一个参数并返回剩余的字符串。 例如,我要删除arg3并最终得到:

$string = http://domain.com/php/doc.php?arg1=0&arg2=1

我将始终希望删除相同的参数( arg3 ),并且它可能不是最后一个参数。

有什么想法吗?

编辑: arg3可能有一堆奇怪的字符,所以我更喜欢这样做的方式(本质上)是:

$newstring = remove $_GET["arg3"] from $string;

这里没有使用正则表达式的真正理由,您可以使用字符串和数组函数代替。

您可以在explodeexplode该零件? (您可以使用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);

请访问http://www.ideone.com/PrO0a实际操作

preg_replace("arg3=[^&]*(&|$)", "", $string)

我假设url本身不包含arg3= ,这在理智的世界中应该是一个安全的假设。

$new = preg_replace('/&arg3=[^&]*/', '', $string);

考虑到例如页面锚点(#)和您提到的至少一些“怪异字符”,但似乎不必担心,这也应该起作用:

function remove_query_part($url, $term)
{
    $query_str = parse_url($url, PHP_URL_QUERY);
    if ($frag = parse_url($url, PHP_URL_FRAGMENT)) {
        $frag = '#' . $frag;
    }
    parse_str($query_str, $query_arr);
    unset($query_arr[$term]);
    $new = '?' . http_build_query($query_arr) . $frag;
    return str_replace(strstr($url, '?'), $new, $url);
}

演示:

$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0#frag';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0&arg4=4';
$string[] = 'http://domain.com/php/doc.php';
$string[] = 'http://domain.com/php/doc.php#frag';
$string[] = 'http://example.com?arg1=question?mark&arg2=equal=sign&arg3=hello';

foreach ($string as $str) {
    echo remove_query_part($str, 'arg3') . "\n";
}

输出:

http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1#frag
http://domain.com/php/doc.php?arg1=0&arg2=1&arg4=4
http://domain.com/php/doc.php
http://domain.com/php/doc.php#frag
http://example.com?arg1=question%3Fmark&arg2=equal%3Dsign

仅如图所示进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM