Modify URL param


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.