Beautiful way to remove GET-variables with PHP?
Ok, to remove all variables, maybe the prettiest is
$url = strtok($url, '?');
See about strtok
here.
Its the fastest (see below), and handles urls without a '?' properly.
To take a url+querystring and remove just one variable (without using a regex replace, which may be faster in some cases), you might do something like:
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;
}
A regex replace to remove a single var might look like:
function removeqsvar($url, $varname) {
return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}
Heres the timings of a few different methods, ensuring timing is reset inbetween runs.
<?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; ";
shows
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 wins, and is by far the smallest code.
Function to remove GET variable with php
Instead of hacking around with regular expression you should parse the string as an url (what it is)
$string = 'index.php?properties&status=av&page=1';
$parts = parse_url($string);
$queryParams = array();
parse_str($parts['query'], $queryParams);
Now just remove the parameter
unset($queryParams['page']);
and rebuild the url
$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
Strip off URL parameter with PHP
The safest "correct" method would be:
- Parse the url into an array with
parse_url()
- Extract the query portion, decompose that into an array using
parse_str()
- Delete the query parameters you want by
unset()
them from the array - Rebuild the original url using
http_build_query()
Quick and dirty is to use a string search/replace and/or regex to kill off the value.
htaccess remove get variable to make better url
These rules check the request line (e.g., "GET /index.html HTTP/1.1")
, the request path is /profile.php
, and if contains the query string lang=&user=
, redirect the request uri from /profile.php
to /profile/%1/%2
, %1
, %2
is the back-reference to match the grouped part ([^&]+)
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /profile\.php
RewriteCond %{QUERY_STRING} lang=([^&]+)&user=([^&]+)
RewriteRule ^/?profile.php$ /profile/%1/%2 [NE,R,L,QSA]
This rule internal rewrite the URL from /profile/{lang}/{user_id}
to /profile.php?lang={lang}&user_id={user_id}
. So when uri /profile/en/1
is requested, the server knows the rewritten uri is /profile.php?lang=en&user_id=1
.
RewriteRule ^/?profile/([^/]+)/([^/]+)$ /profile.php?lang=$1&user_id=$2 [L]
Remove GET parameter from url with php
Here's a fiddle.
Works for PHP 5.3+
// Make array from query string
// If using the url from a string
$str = "www.domain.com/blog?date[]=thedate&date[]=thesnddate&title=sometitle";
parse_str(explode("?", $str)[1], $params);
// If using the query string from the current url...
//parse_str($_SERVER['QUERY_STRING'], $params);
// Remoove one of the dates
unset($params['date'][0]);
// Re-create the url
$newDomain = "www.domain.com/blog?".http_build_query($params);
print_r($newDomain);
Related Topics
Prevent Innodb Auto Increment on Duplicate Key
PHP Send E-Mail with Attachment
Automatic Image Format Detection in PHP
How to Use Objects from Other Namespaces and How to Import Namespaces in PHP
How to Display a MySQL Error in PHP for a Long Query That Depends on the User Input
Calculate the Time When the Sun Is X Degrees Below/Above the Horizon
Phpmyadmin - Count(): Parameter Must Be an Array or an Object That Implements Countable
Disable Deprecated Warning in Symfony 2(.7)
Use a Variable to Define a PHP Function
"Connection for Controluser as Defined in Your Configuration Failed" with PHPmyadmin in Xampp
More Concise Way to Check to See If an Array Contains Only Numbers (Integers)
Caching Http Responses When They Are Dynamically Created by PHP
The Post Method Is Not Supported for This Route. Supported Methods: Get, Head. Laravel
Shorthand for Arrays: Is There a Literal Syntax Like {} or []