note 60237 deleted from function.parse-url by didou

From: Date: Sat, 03 Feb 2007 03:07:25 +0000
Subject: note 60237 deleted from function.parse-url by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-122614@lists.php.net to get a copy of this message
Note Submitter: greg dot linton at gmail dot com ---- I needed to work both ways (adding & deleteing) query items to the url. Corey's function worked well for adding, but I needed the opposite. I modifed his to work for both ways leaving me with this: <?php /** * Edit the Query portion of an url * * @param string $action ethier a "+" or a "-" depending on what action you want to perform * @param mixed $var array (+) or string (-) * @param string $uri the URL to use. if this is left out, it uses $_SERVER['PHP_SELF'] * @version 1.0.0 */ function ChangeQuery($action, $var = NULL, $uri = NULL) { if (($action == "+" && ! is_array($var)) || ($action == "-" && $var == "") || $var == NULL) return FALSE; if (is_null($uri)) {//Piece together uri string $beginning = $_SERVER['PHP_SELF']; $ending = ( isset($_SERVER['QUERY_STRING']) ) ? $_SERVER['QUERY_STRING'] : ''; } else { $qstart = strpos($uri, '?'); if ($qstart === false) { $beginning = $uri; //$ending is '' anyway } else { $beginning = substr($uri, 0, $qstart); $ending = substr($uri, $qstart); } } if (strlen($ending) > 0) { $vals = array(); $ending = str_replace('?','', $ending); parse_str($ending, $vals); if ($action == "+") $vals[$var[0]] = $var[1]; $ending = ''; $count = 0; foreach($vals as $k => $v) { if ($action == "-" && $k == $var) continue; if ($count > 0) { $ending .= '&'; } else { $count++; } $ending .= "$k=" . urlencode($v); } } else { $ending = $varName . '=' . urlencode($varVal); } $result = $beginning . '?' . $ending; return $result; } ?> with this test: <?php $url = "http://www.somesite.com/somepage.php?id=53&sec=1&sort=up"; $url = ChangeQuery("+",array("test",5),$url); echo $url."<br>"; $url = ChangeQuery("-","sort", $url); echo $url."<br>"; $url = ChangeQuery("-","test", $url); echo $url."<br>"; $url = ChangeQuery("+",array("sort","dn"), $url); echo $url."<br>"; ?> I got http://www.somesite.com/somepage.php?id=53&sec=1&sort=up&test=5 http://www.somesite.com/somepage.php?id=53&sec=1&test=5 http://www.somesite.com/somepage.php?id=53&sec=1 http://www.somesite.com/somepage.php?id=53&sec=1&sort=dn ?> If you're adding to the url, the second argument has to be an array, where the first element is the name and the second is the value. If you're deleting from the query, it's the name of var to delete I hope this helps somebody down the line.

« previous php.notes (#122614) next »