正则表达式:从URL中删除某些参数和值

时间:2016-11-21 02:57:19

标签: php regex

如何从网址中删除某些参数及其值?

<?php $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>

我的网址可以是pagename?page=2pagename?param=235235&page=2pagename?page=10&param=5431等。

我需要从网址中删除page=x

3 个答案:

答案 0 :(得分:1)

  

您已在问题中声明要删除page = xx   网址。

下午没有什么像正则表达式的气味......所以我对此进行了抨击,以下情况应该可以解决问题。

我确信它可以更聪明地完成,但它可以让你开始运行。

<?php
/*
 * My urls can be
 * pagename?page=2 or
 * pagename?param=235235&page=2 or
 * pagename?page=10&param=5431 or etc.
 */
function remove_page_from_url($url){
    // For the case where ?page=xx&param
    if (preg_match('/\?page=[0-9]{0,}&/',$url)){
        $url =  preg_replace('/&/','?',$url,1); // Only replace the 1st one.
    }
    return preg_replace('/[\?|&]page=[0-9]{0,}/','',$url);
}

// The Testing during development

//Case 1: This works
$url = 'pagename?page=10';
echo remove_page_from_url($url);
echo '<br>';

//Case 2: This works
$url = 'pagename?param=235235&page=2';
echo remove_page_from_url($url);
echo '<br>';

//Case 3: This works
//This messes things up as we also have to change a & to a ?
$url = 'pagename?page=10&param=5431';
echo remove_page_from_url($url);
echo '<br>';

//Case 4: This Works
//This messes things up as we also have to change a & to a ? but only the first one.
$url = 'pagename?page=10&param=5431&something=2';
echo remove_page_from_url($url);
echo '<br>';

所以你从最简单的案例开始,一路向上。

/*
The Results

pagename?page=10
=>   pagename

pagename?param=235235&page=2
=>   pagename?param=235235

pagename?page=10&param=5431
=>   pagename?param=5431

pagename?page=10&param=5431&something=2
=>   pagename?param=5431&something=2
*/

因此,您感兴趣的是函数remove_page_from_url($url)内的代码。

答案 1 :(得分:1)

Remove dynamic parameters from a URL

 <?php
function remove_url_parmeter($url,$parameter_key){
        if($parameter_key && $url){
            foreach($parameter_key as $val){
                 if (preg_match('/[\?|&]'.$val.'=[0-9]{0,}/',$url)){
                    $url =  preg_replace('/&/','?',$url,1);
                 }
                 $url = preg_replace('/[\?|&]'.$val.'=[0-9]{0,}/','',$url);
            }
        }else{
            $url = 'This is not work';
        }
    return $url;

}

$url = "http://example.com/pagename?page=5&param=5431&page1=10&somepage=3";
//$parameter_key =array('page','page1');
echo remove_url_parmeter($url,array('page','page1'));

?>

答案 2 :(得分:1)

使用php的内置url函数而不使用正则表达式的另一种方法。更优雅的恕我直言

function removeParamFromURL($param, $url) {
    $parsed_url = parse_url($url);
    parse_str($parsed_url["query"], $querystringarray);
    unset($querystringarray[$param]);
    $parsed_url["query"] = http_build_query($querystringarray);
    return $parsed_url["scheme"] . "://" . $parsed_url["host"] . $parsed_url["path"] . "?" . $parsed_url["query"];
}
$url = "http://example.com/aaa/bbb/pagename/page.php?param=235235&page=2";
print $finalurl = removeParamFromURL("page", $url);