note 108358 added to reserved.variables.get

From: Date: Thu, 19 Apr 2012 17:44:18 +0000
Subject: note 108358 added to reserved.variables.get
Groups: php.notes 
Request: Send a blank email to php-notes+get-187242@lists.php.net to get a copy of this message
A way of removing keys from $_GET - in my opinion - in a more elegant way is by using regular expressions. I must note, that for better performance, I only use non capturing groupings: (?:... ) <?php /** * Remove one or more keys from the URL * @author Mészáros Lajos György * @param $key : Key( string ) or keys( array of strings ) that you want to remove */ function remove_from_url($key){ if(is_array($key)) $key = '(?:'.implode('|', $key).')'; $url = preg_replace('/(?:&|(?<=\?))'.$key.'(?:=[^&]*?)?(?=(?:&|$))/', '', $_SERVER['REQUEST_URI']); return preg_replace('/(?<=\?)&|\?$/', '', $url); } ?> So let's assume you have the following URL: something.php?a=12&b=134&c=foo <?php echo remove_key_from_url('c'); // will become: something.php?a=12&b=134 echo remove_key_from_url('a'); // will become: something.php?b=134&c=foo // Note: if key is next to ?, then it will remove the following & sign, so the URL will not become something.php?&b=134&c=foo - ( that is what the 3rd line is for ) echo remove_key_from_url(Array('a', 'b', 'c')); // will become: something.php // Note: the 3rd line will remove the single ? from the end // current url here is: /foo/bar/?something&a=3 echo remove_key_from_url('something'); // will become: /foo/bar/?a=3 // Note: the code can handle if no value is assigned to a key ?> After this, you only need to pass the returned string to a header and then kill the page: <?php // current URL is admin.php?logout header('Location'.remove_key_from_url('logout')); ?> I need to add, that I didn't do any benchmarks upon testing whether is this the faster or doing a bunch of explodes and working with arrays. Also, I don't think it is possible to combine the two regexes into a single one, because the regex in the 3rd line needs to be executed after all key-value removals are done, but if possible, please give me an e-mail, I'm really interested. Louis from Hungary ---- Server IP: 69.147.83.197 Probable Submitter: 178.48.17.65 ---- Manual Page -- http://www.php.net/manual/en/reserved.variables.get.php Edit -- https://master.php.net/note/edit/108358 Del: integrated -- https://master.php.net/note/delete/108358/integrated Del: useless -- https://master.php.net/note/delete/108358/useless Del: bad code -- https://master.php.net/note/delete/108358/bad+code Del: spam -- https://master.php.net/note/delete/108358/spam Del: non-english -- https://master.php.net/note/delete/108358/non-english Del: in docs -- https://master.php.net/note/delete/108358/in+docs Del: other reasons-- https://master.php.net/note/delete/108358 Reject -- https://master.php.net/note/reject/108358 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#187242) next »