dp0518 2013-06-21 16:48
浏览 25
已采纳

preg_replace for Get Parameter - /index.php?color=blue&size=xl

I have this url /index.php?color=blue&size=xl

to get rid of the get parameter, I use this code:

$done = preg_replace('/(.*)(\?|&)color=[^&]*(?(1)&|)?/i', "$1", $url);
echo $done;
"output: index.phpsize=xl"

Now I need to clean the "size" part too. Have tried with two lines of preg_replace, but it doesn´t work.

$done = preg_replace('/(.*)(\?|&)color=[^&]*(?(1)&|)?/i', "$1", $url);
echo $done;
$done2 = preg_replace('/(.*)(\?|&)size=[^&]*(?(1)&|)?/i', "$1", $done);

Edit: I really need a solution where I can clean the exact parameter "color" or "size".

Sometimes I will only delete one of them.

Edit2: Have this solution:

// Url is: index.php?color=black&size=xl&price=20

function removeqsvar($url, $varname) {
return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}
$url = removeqsvar($url, color);
echo removeqsvar($url, price);

// will output: index.php?size=xl

Thank you all.

  • 写回答

3条回答 默认 最新

  • drnf09037160 2013-06-21 17:24
    关注

    This will allow you to exactly specify which parameters to remove using the $remove array. It works by parsing the URL with parse_url(), then grabbing the query string and parsing it with parse_str().

    From there, it's straightforward - Iterate over the parameters in the URL, if one of them is in the $remove array, then delete it from the $params array. By the end, if we have parameters to add to the URL, we add them back with http_build_query().

    $url = '/index.php?color=blue&size=xl'; // Your input URL
    $remove = array( 'color', 'size'); // Change this to remove what you want
    
    $parts = parse_url( $url);
    parse_str( $parts['query'], $params);
    
    foreach( $params as $k => $v) {
        if( in_array( $k, $remove)) {
            unset( $params[$k]);
        }
    }
    
    $url = $parts['path'] . ((count( $params) > 0) ? '?' . http_build_query( $params) : '');
    echo $url;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据