Posted By

mikael12 on 12/19/10


Tagged

modify-url-param


Versions (?)

Modify URL param


 / Published in: PHP
 

URL: http://www.phpsnippets.info/easily-modify-url-parameters

Current URL http://www.example.com/page.php?p=5&show=list&style=2 and after $url = modify_url(array('p' => 4, 'show' => 'column')); URL will become http://www.example.com/page.php?p=4&show=column&style=2

  1. function modify_url($mod){
  2. $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  3. $query = explode("&", $_SERVER['QUERY_STRING']);
  4. if (!$_SERVER['QUERY_STRING']) {$queryStart = "?";} else {$queryStart = "&";}
  5. // modify/delete data
  6. foreach($query as $q)
  7. {
  8. list($key, $value) = explode("=", $q);
  9. if(array_key_exists($key, $mod))
  10. {
  11. if($mod[$key])
  12. {
  13. $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
  14. }
  15. else
  16. {
  17. $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
  18. }
  19. }
  20. }
  21. // add new data
  22. foreach($mod as $key => $value)
  23. {
  24. if($value && !preg_match('/'.$key.'=/', $url))
  25. {
  26. $url .= $queryStart.$key.'='.$value;
  27. }
  28. }
  29. return $url;
  30. }

Report this snippet  

You need to login to post a comment.