用 PHP 去除 URL 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4937478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:18:17  来源:igfitidea点击:

Strip off URL parameter with PHP

php

提问by tpow

I have some links in a powerpoint presentation, and for some reason, when those links get clicked, it adds a return parameter to the URL. Well, that return parameter is causing my Joomla site's MVC pattern to get bungled.

我在 powerpoint 演示文稿中有一些链接,出于某种原因,当这些链接被点击时,它会向 URL 添加一个返回参数。好吧,该返回参数导致我的 Joomla 站点的 MVC 模式变得笨拙。

So, what's an efficient way to strip off this return parameter using PHP...?

那么,使用 PHP 去除这个返回参数的有效方法是什么......?

Example: http://mydomain.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0

示例:http: //mydomain.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0

回答by Marc B

The safest "correct" method would be:

最安全的“正确”方法是:

  1. Parse the url into an array with parse_url()
  2. Extract the query portion, decompose that into an array using parse_str()
  3. Delete the query parameters you want by unset()them from the array
  4. Rebuild the original url using http_build_query()
  1. 将 url 解析为一个数组 parse_url()
  2. 提取查询部分,使用 parse_str()
  3. unset()从数组中删除他们想要的查询参数
  4. 使用重建原始网址 http_build_query()

Quick and dirty is to use a string search/replace and/or regex to kill off the value.

快速而肮脏的是使用字符串搜索/替换和/或正则表达式来消除该值。

回答by Lars Koudal

In a different thread Justin suggests that the fastest way is to use strtok()

在另一个线程中贾斯汀建议最快的方法是使用strtok()

 $url = strtok($url, '?');

See his full answer with speed tests as well here: https://stackoverflow.com/a/1251650/452515

也可以在这里查看他的完整速度测试答案:https: //stackoverflow.com/a/1251650/452515

回答by Sergey Telshevsky

This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number

这是用一个例子补充Marc B的答案,虽然它可能看起来很长,但它是删除参数的安全方法。在这个例子中,我们删除page_number

<?php
$x = 'http://url.com/search/?location=london&page_number=1';

$parsed = parse_url($x);
$query = $parsed['query'];

parse_str($query, $params);

unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);

回答by NikiC

parse_str($queryString, $vars);
unset($vars['return']);
$queryString = http_build_query($vars);

parse_strparses a query string, http_build_querycreates a query string.

parse_str解析查询字符串,http_build_query创建查询字符串。

回答by kraftb

function removeParam($url, $param) {
    $url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*$/', '', $url);
    $url = preg_replace('/(&|\?)'.preg_quote($param).'=[^&]*&/', '', $url);
    return $url;
}

回答by Aaron Hathaway

You could do a preg_replacelike:

你可以这样做preg_replace

$new_url = preg_replace('/&?return=[^&]*/', '', $old_url);

回答by Chuck Morris

This one of many ways, not tested, but should work.

这是许多方法中的一种,未经测试,但应该有效。

$link = 'http://mydomain.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0';
$linkParts = explode('&return=', $link);
$link = $linkParts[0];

回答by shazyriver

Procedural Implementation of Marc B'sAnswer after refining Sergey Telshevsky'sAnswer.

改进Sergey Telshevsky'sAnswer后Marc B'sAnswer 的程序实施。

function strip_param_from_url( $url, $param )
{
    $base_url = strtok($url, '?');              // Get the base url
    $parsed_url = parse_url($url);              // Parse it 
    $query = $parsed_url['query'];              // Get the query string
    parse_str( $query, $parameters );           // Convert Parameters into array
    unset( $parameters[$param] );               // Delete the one you want
    $new_query = http_build_query($parameters); // Rebuilt query string
    return $base_url.'?'.$new_query;            // Finally url is ready
}

// Usage
echo strip_param_from_url( 'http://url.com/search/?location=london&page_number=1', 'location' )

回答by doublejosh

Here is the actual code for what's described above as the "the safest 'correct' method"...

这是上面描述的“最安全的'正确'方法”的实际代码......

function reduce_query($uri = '') {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        return $new_uri;
    }
    return $uri;
}

$_SERVER['REQUEST_URI'] = reduce_query($_SERVER['REQUEST_URI']);

However, since this will likely exist prior to the bootstrap of your application, you should probably put it into an anonymous function. Like this...

但是,由于这可能在您的应用程序引导之前存在,您可能应该将其放入匿名函数中。像这样...

call_user_func(function($uri) {
    $kill_params = array('gclid');

    $uri_array = parse_url($uri);
    if (isset($uri_array['query'])) {
        // Do the chopping.
        $params = array();
        foreach (explode('&', $uri_array['query']) as $param) {
          $item = explode('=', $param);
          if (!in_array($item[0], $kill_params)) {
            $params[$item[0]] = isset($item[1]) ? $item[1] : '';
          }
        }
        // Sort the parameter array to maximize cache hits.
        ksort($params);
        // Build new URL (no hosts, domains, or fragments involved).
        $new_uri = '';
        if ($uri_array['path']) {
          $new_uri = $uri_array['path'];
        }
        if (count($params) > 0) {
          // Wish there was a more elegant option.
          $new_uri .= '?' . urldecode(http_build_query($params));
        }
        // Update server variable.
        $_SERVER['REQUEST_URI'] = $new_uri;

    }
}, $_SERVER['REQUEST_URI']);

NOTE: Updated with urldecode()to avoid double encoding via http_build_query()function. NOTE: Updated with ksort()to allow params with no value without an error.

注意:更新urldecode()为避免双重编码via http_build_query()功能。注意:更新ksort()为允许没有值的参数没有错误。

回答by ptmalcolm

Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!

哇,这里有很多例子。我提供了一个进行一些错误处理的。它重建并返回整个 URL,其中删除了 query-string-param-to-be-removed 。它还提供了一个额外的功能,可以即时构建当前的 URL。经测试,有效!

Credit to Mark Bfor the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)

归功于Mark B的步骤。这是tpow的“剥离此返回参数”原始问题的完整解决方案- 可能对初学者很方便,试图避免 PHP 陷阱。:-)

<?php

function currenturl_without_queryparam( $queryparamkey ) {
    $current_url = current_url();
    $parsed_url = parse_url( $current_url );
    if( array_key_exists( 'query', $parsed_url )) {
        $query_portion = $parsed_url['query'];
    } else {
        return $current_url;
    }

    parse_str( $query_portion, $query_array );

    if( array_key_exists( $queryparamkey , $query_array ) ) {
        unset( $query_array[$queryparamkey] );
        $q = ( count( $query_array ) === 0 ) ? '' : '?';
        return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
    } else {
        return $current_url;
    }
}

function current_url() {
    $current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
    return $current_url;
}

echo currenturl_without_queryparam( 'key' );

?>