PHP remove a couple with one variable from querystring

I have a page that lists items by numerous parameters, i.e. variables with values.

listitems.php?color=green&size=small&cat=pants&pagenum=1 etc. 

To enable list editing, I have an edit = 1 parameter, which is added to the above sequence:

 listitems.php?color=green&size=small&cat=pants&pagenum=1&edit=1 

So far so good.

When the user has finished editing, I have a link that exits the editing mode. I want this link to indicate the entire sequence of requests — whatever it is, since it depends on the user's choice — other than deleting edit = 1.

When I had only a few variables, I simply listed them manually by reference, but now that there is more, I would like to be able to programmatically just delete edit = 1.

Should I do some kind of search for edit = 1, and then just replace it with nothing?

 $qs = str_replace("&edit=1, "", $_SERVER['QUERY_STRING']); <a href='{$_SERVER['PHP_SELF']}?{$qs}'>return</a>; 

Or, what would be the cleanest, most error-free way to do it.

Note. I have a similar situation when switching from page to page where I would like to take out pagenum and replace it with another. There, since pagenum is changing, I can't just look for pagenum = 1, but you have to look for pagenum =$pagenum , if that matters.

Thanks.

+6
source share
3 answers

I would use http_build_query , which takes an array of parameters perfectly and formats it correctly. You could disable the edit option from $_GET and press the rest of this function.

Note that your code htmlspecialchars() not have a htmlspecialchars() call. A URL may contain characters that are active in HTML. Therefore, putting it in the link: Escape!

Example:

 unset($_GET['edit']); // delete edit parameter; $_GET['pagenum'] = 5; // change page number $qs = http_build_query($_GET); ... output link here. 
+16
source

Another solution to avoid problems with &amp; !!!

 remove_query('http://example.com/?a=valueWith**&amp;**inside&b=value'); 

code:

 function remove_query($url, $which_argument=false){ return preg_replace('/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url); } 
+2
source

This will not work if edit=1 is the first variable:

 listitems.php?edit=1&color=green&... 

You can use the $_GET variable to create the query string yourself. Sort of:

 $qs = ''; foreach ($_GET as $key => $value){ if ($key == 'pagenum'){ // Replace page number $qs .= $key . '=' . $new_page_num . '&'; }elseif ($key != 'edit'){ // Keep all key/values, except 'edit' $qs .= $key . '=' . urlencode($value) . '&'; } } 
0
source

Source: https://habr.com/ru/post/947360/


All Articles