Удалить get параметры php

Function to remove GET variable with php

i would want to remove the last variable from the string i.e &page=1 . please note the value for page will not always be 1 . keeping this in mind i would want to trim the variable this way.

Update : I would like to remove &page=1 from the string, no matter in which position it is on. how do i do this?

6 Answers 6

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

$queryString = http_build_query($queryParams); $url = $parts['path'] . '?' . $queryString; 

You can also do parse_str(html_entity_decode($parts[‘query’]), $queryParams); to preserve the & when echo’ing it out

There are many roads that lead to Rome. I’d do it with a RegEx:

$myString = 'index.php?properties&status=av&page=1'; $myNewString = preg_replace("/\&[a-z0-9]+=4+$/i","",$myString); 

if you only want the &page=1 -type parameters, the last line would be

$myNewString = preg_replace("/\&page=7+/i","",$myString); 

if you also want to get rid of the possibility that page is the only or first parameter:

$myNewString = preg_replace("/[\&]*page=4+/i","",$myString); 

i appreciate your help and sorry for not mentioning this before but this will only remove the last variable from the string, wheras i am looking to remove the &page=1 variable regardless of it’s position.

index.php?momomomooonsterpage=123&properties&status=av ? (=> index.php?momomomooonster&properties&status=av ;)) Regular expressions have many pitfalls. I don’t want to embarrass you, but such things often leads to weird behavior later, that are hard to track down.

Thank you guys but i think i have found the better solution, @KingCrunch had suggested a solution i extended and converted it into function. the below function can possibly remove or unset any URI variable without any regex hacks being used. i am posting it as it might help someone.

function unset_uri_var($variable, $uri)

now consider the following uri

index.php?properties&status=av&page=1 //To remove properties variable $url = unset_uri_var('properties', basename($_SERVER['REQUEST_URI'])); //Outputs index.php?page=1&status=av //To remove page variable $url = unset_uri_var('page', basename($_SERVER['REQUEST_URI'])); //Outputs index.php?properties=&status=av 

hope this helps someone. and thank you @KingKrunch for your solution 🙂

$pos = strrpos($_SERVER['REQUEST_URI'], '&'); $url = substr($_SERVER['REQUEST_URI'], 0, $pos - 1); 

although this will work but it will just remove the last Variable. i am sorry for not stating this before but i would like to trim $page=1 regardless of it’s position it may occur before status=av or after.

@root45 . you could at least have the motivation to change my variable name before you ‘rip off’ my post directly below 😉

index.php?properties&status=av index.php?properties&status=av index.php? 

i appreciate that @Gabi Purcaru, or how about the extended solution from KingCrunch, check my answer.

You could use a RegEx (as Chris suggests) but it’s not the most efficient solution (lots of overhead using that engine. it’s easy to do with some string parsing:

"; //Find the last ampersand $lastAmp=strrpos($base,"&"); //Filter, catch no ampersands found $removeLast=($lastAmp===false?$base:substr($base,0,$lastAmp)); echo "Without Last Parameter: $removeLast
"; ?>

The trick is, can you guarantee that $page will be stuck on the end? If it is — great, if it isn’t. what you asked for may not always solve the problem.

Источник

Beautiful way to remove GET-variables with PHP?

I have a string with a full URL including GET variables. Which is the best way to remove the GET variables? Is there a nice way to remove just one of them? This is a code that works but is not very beautiful (I think):

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

The code above just removes all the GET variables. The URL is in my case generated from a CMS so I don’t need any information about server variables.

I would stick with what you have unless performance is not an issue. The regex solution supplied by Gumbo is going to be be as pretty as it gets.

It Doesn’t need to be beautiful if it’s going in functions.php or whereever you hide your ugly bits, you’ll only need to see qs_build() to call it

How about the url fragment? The solutions I see below all discard the fragment as well, just as your code does.

12 Answers 12

Ok, to remove all variables, maybe the prettiest is

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)

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.

 $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 wins, and is by far the smallest code.

Источник

PHP unset get parameter?

I’m using this function to determine the current URL of the page. I want to know if it is possible to extend this function to unset a pre-determined $_GET parameter. All of my $_GET values are stored in an array. So I can access the specific values by using

Is it expensive and not realistic to use my suggested logic to accomplish this task? EDIT: I only want to print the URL to use it as a link.
My url has GET parameters in it.

6 Answers 6

Not sure what you really want to do with this, but $_GET (and other super-globals) are not read-only :

  • You can add values into them,
  • You can overide values,
  • And, of course, you can unset() values.

Note, though, that modifying $_GET is often not considered as good-practice : when one reads some code, he expects what’s in $_GET to come from the parameters in the URL — and not from your code.

For instance, you can absolutely do something like this :

function getUrlCurrently($filter = array()) < $pageURL = isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on" ? "https://" : "http://"; $pageURL .= $_SERVER["SERVER_NAME"]; if ($_SERVER["SERVER_PORT"] != "80") < $pageURL .= ":".$_SERVER["SERVER_PORT"]; >$pageURL .= $_SERVER["REQUEST_URI"]; if (strlen($_SERVER["QUERY_STRING"]) > 0) < $pageURL = rtrim(substr($pageURL, 0, -strlen($_SERVER["QUERY_STRING"])), '?'); >$query = $_GET; foreach ($filter as $key) < unset($query[$key]); >if (sizeof($query) > 0) < $pageURL .= '?' . http_build_query($query); >return $pageURL; > // gives the url as it is echo getUrlCurrently(); // will remove 'foo' and 'bar' from the query if existent echo getUrlCurrently(array('foo', 'bar')); 

To assemble a link with GET parameters in an array try:

unset($my_array['key']); $url = getUrlCurrently() . '?' . http_build_query($my_array); 

This has nthg to do with $_GET. You can just use the existing global data $_SERVER, or getenv, like this :

function GetCurrentUrl($debug=FALSE) < $pageURL = (strtolower($_SERVER["HTTPS"]) == "on") ? "https://" : "http://"; if ($_SERVER["SERVER_PORT"] != "80") < $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; >else < $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; >// DEBUG if ($debug) < $msg = "DEBUG MODE: current URL http://php.net/manual/en/function.http-build-query.php" rel="nofollow">http_build_query

EDIT2: On top of that, with regards to one point of your question, you can also add a work around to setup a "rewriting"-like function as described in this php manual interesting example.

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Jul 26, 2011 at 22:35
answered Jul 26, 2011 at 11:18
Add a comment |
0

Wouldn't it be easier to user $_SERVER['SCRIPT_URI']?
It returns the full url without query parameters.

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Jul 26, 2011 at 11:11
Add a comment |
0
//your query string is ?a=1&b=2&c=3 function unset_get($param) < //sets string to (array) $query_string parse_str($_SERVER['QUERY_STRING'],$query_string); //removes array element defined by param unset($query_string[$param]); //returns modified array as a string return http_build_query($query_string); >print unset_get( 'b'); //returns "a=1&c=3" 

Источник

remove GET parameter in URL after processing is finished(not using POST), PHP

I have url like this http://localhost/join/prog/ex.php When i use GET method the url address like this http://localhost/join/prog/ex.php?name=MEMORY+2+GB&price=20&quantity=2&code=1&search=add My question is : so, I still use the GET method but I want to after processing in GET method is finished, I want to the url back(remove parameter) into http://localhost/join/prog/ex.php , as previously (not using POST method). How can i do it?

@pekka: No redirect, but i want to remove parameter when finished using GET method(just remove parameter)

Brad, sometimes, people have needs that you don't understand (and that are none of your business). My website uses only one page wich is dynamically manipulated using ajax. My webpage is essentially never refreshed. I now need to send an email that will contain a link that, when clicked, will navigate directly to a subsection of the site and load an object. From an email, I can't use javascript. So I cannot send a POST to my page. This means I have to send a GET. But since the page is never refreshed, the GET params would stay in the address forever and cause issues when F5 is pressed.

Bottom line is: When we ask questions, we want answers. Not opinions. Just because what he tries to do makes no sense in YOUR projects doesn't mean it doesn't make sense in THEIR projects. You could also argue that my project is bad, that I should have distinct pages and not a single ajax-refreshed page. But again, you would be talking about things you don't know. I didn't start this project, and I didn't choose to use such a framework. I have taken this project over from other people, and now I'm stuck with it. So please. Give answers, not opinions. Thank you.

Источник

Читайте также:  Java se platform crfxfnm
Оцените статью