Прекрасный способ удалить GET-переменные с помощью PHP? - PullRequest
83 голосов
/ 09 августа 2009

У меня есть строка с полным URL, включая переменные GET. Какой лучший способ удалить переменные GET? Есть ли хороший способ удалить только один из них?

Это код, который работает, но не очень красивый (я думаю):

$current_url = explode('?', $current_url);
echo $current_url[0];

Приведенный выше код просто удаляет все переменные GET. В моем случае URL создается из CMS, поэтому мне не нужна информация о серверных переменных.

Ответы [ 11 ]

214 голосов
/ 09 августа 2009

Хорошо, чтобы удалить все переменные, возможно, самый красивый -

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

См. strtok здесь .

Это самый быстрый (см. Ниже), и обрабатывает URL без '?' должным образом.

Чтобы взять строку url + query и удалить только одну переменную (без использования замены регулярного выражения, которая может быть быстрее в некоторых случаях), вы можете сделать что-то вроде:

function removeqsvar($url, $varname) {
    list($urlpart, $qspart) = array_pad(explode('?', $url), 2, '');
    parse_str($qspart, $qsvars);
    unset($qsvars[$varname]);
    $newqs = http_build_query($qsvars);
    return $urlpart . '?' . $newqs;
}

Замена регулярного выражения для удаления одной переменной может выглядеть следующим образом:

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

Здесь приведены временные параметры нескольких различных методов, обеспечивающих сброс времени между циклами.

<?php

$number_of_tests = 40000;

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;

for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    preg_replace('/\\?.*/', '', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "regexp execution time: ".$totaltime." seconds; ";

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    $str = explode('?', $str);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "explode execution time: ".$totaltime." seconds; ";

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    $qPos = strpos($str, "?");
    $url_without_query_string = substr($str, 0, $qPos);
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "strpos execution time: ".$totaltime." seconds; ";

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
for($i = 0; $i < $number_of_tests; $i++){
    $str = "http://www.example.com?test=test";
    $url_without_query_string = strtok($str, '?');
}
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "tok execution time: ".$totaltime." seconds; ";

показывает

regexp execution time: 0.14604902267456 seconds; explode execution time: 0.068033933639526 seconds; strpos execution time: 0.064775943756104 seconds; tok execution time: 0.045819044113159 seconds; 
regexp execution time: 0.1408839225769 seconds; explode execution time: 0.06751012802124 seconds; strpos execution time: 0.064877986907959 seconds; tok execution time: 0.047760963439941 seconds; 
regexp execution time: 0.14162802696228 seconds; explode execution time: 0.065848112106323 seconds; strpos execution time: 0.064821004867554 seconds; tok execution time: 0.041788101196289 seconds; 
regexp execution time: 0.14043688774109 seconds; explode execution time: 0.066350221633911 seconds; strpos execution time: 0.066242933273315 seconds; tok execution time: 0.041517972946167 seconds; 
regexp execution time: 0.14228296279907 seconds; explode execution time: 0.06665301322937 seconds; strpos execution time: 0.063700199127197 seconds; tok execution time: 0.041836977005005 seconds; 

strtok выигрывает и является наименьшим кодом.

30 голосов
/ 09 августа 2009

Как насчет:

preg_replace('/\\?.*/', '', $str)
9 голосов
/ 09 августа 2009

Если URL-адрес, с которого вы пытаетесь удалить строку запроса, является текущим URL-адресом сценария PHP, вы можете использовать один из ранее упомянутых методов. Если у вас есть строковая переменная с URL-адресом, и вы хотите удалить все, что находится после символа «?» Вы можете сделать:

$pos = strpos($url, "?");
$url = substr($url, 0, $pos);
7 голосов
/ 09 августа 2009

Вдохновленный комментарием @MitMaro, я написал небольшой тест для проверки скорости решений @Gumbo, @Matt Bridges и @justin предложения в вопросе:

function teststrtok($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      $str = strtok($str,'?');
    }
}
function testexplode($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      $str = explode('?', $str);
    }
}
function testregexp($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      preg_replace('/\\?.*/', '', $str);
    }
}
function teststrpos($number_of_tests){
    for($i = 0; $i < $number_of_tests; $i++){
      $str = "http://www.example.com?test=test";
      $qPos = strpos($str, "?");
      $url_without_query_string = substr($str, 0, $qPos);
    }
}

$number_of_runs = 10;
for($runs = 0; $runs < $number_of_runs; $runs++){

  $number_of_tests = 40000;
  $functions = array("strtok", "explode", "regexp", "strpos");
  foreach($functions as $func){
    $starttime = microtime(true);
    call_user_func("test".$func, $number_of_tests);
    echo $func.": ". sprintf("%0.2f",microtime(true) - $starttime).";";
  }
  echo "<br />";
}
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;

Результат: стрельба @ Джастина самая быстрая.

Примечание: протестировано в локальной системе Debian Lenny с Apache2 и PHP5.

6 голосов
/ 03 июля 2015

Другое решение ... Я нахожу эту функцию более элегантной, она также удалит завершающий "?" если удаляемый ключ - единственный в строке запроса.

/**
 * Remove a query string parameter from an URL.
 *
 * @param string $url
 * @param string $varname
 *
 * @return string
 */
function removeQueryStringParameter($url, $varname)
{
    $parsedUrl = parse_url($url);
    $query = array();

    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $query);
        unset($query[$varname]);
    }

    $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
    $query = !empty($query) ? '?'. http_build_query($query) : '';

    return $parsedUrl['scheme']. '://'. $parsedUrl['host']. $path. $query;
}

Тесты:

$urls = array(
    'http://www.example.com?test=test',
    'http://www.example.com?bar=foo&test=test2&foo2=dooh',
    'http://www.example.com',
    'http://www.example.com?foo=bar',
    'http://www.example.com/test/no-empty-path/?foo=bar&test=test5',
    'https://www.example.com/test/test.test?test=test6',
);

foreach ($urls as $url) {
    echo $url. '<br/>';
    echo removeQueryStringParameter($url, 'test'). '<br/><br/>';
}

Будет выводить:

http://www.example.com?test=test
http://www.example.com

http://www.example.com?bar=foo&test=test2&foo2=dooh
http://www.example.com?bar=foo&foo2=dooh

http://www.example.com
http://www.example.com

http://www.example.com?foo=bar
http://www.example.com?foo=bar

http://www.example.com/test/no-empty-path/?foo=bar&test=test5
http://www.example.com/test/no-empty-path/?foo=bar

https://www.example.com/test/test.test?test=test6
https://www.example.com/test/test.test

"Выполнить эти тесты на 3v4l

3 голосов
/ 25 апреля 2013

Не могли бы вы использовать переменные сервера для этого?

Или это сработает?:

unset($_GET['page']);
$url = $_SERVER['SCRIPT_NAME'] ."?".http_build_query($_GET);

Просто мысль.

2 голосов
/ 09 августа 2009

Для этого можно использовать серверные переменные , например $_SERVER['REQUEST_URI'] или даже лучше: $_SERVER['PHP_SELF'].

0 голосов
/ 01 февраля 2017

На мой взгляд, лучшим способом было бы это:

<? if(isset($_GET['i'])){unset($_GET['i']); header('location:/');} ?>

Он проверяет, есть ли параметр GET 'i', и удаляет его, если он есть.

0 голосов
/ 04 апреля 2014

basename($_SERVER['REQUEST_URI']) возвращает все после и включая '?',

В моем коде иногда мне нужны только разделы, поэтому выделите их, чтобы я мог получить значение того, что мне нужно, на лету. Не уверен в быстродействии по сравнению с другими методами, но это действительно полезно для меня.

$urlprotocol = 'http'; if ($_SERVER["HTTPS"] == "on") {$urlprotocol .= "s";} $urlprotocol .= "://";
$urldomain = $_SERVER["SERVER_NAME"];
$urluri = $_SERVER['REQUEST_URI'];
$urlvars = basename($urluri);
$urlpath = str_replace($urlvars,"",$urluri);

$urlfull = $urlprotocol . $urldomain . $urlpath . $urlvars;
0 голосов
/ 02 августа 2010
@list($url) = explode("?", $url, 2);
...