PHP URL parsing


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



Copy this code and paste it in your HTML
  1. <?php
  2. $x = "/blog/index/1?foo=2&bar=4";
  3. //$x = "/blog/index/1";
  4. $x = preg_replace('#^/(.*)#', "$1", $x );
  5.  
  6. $url_data = explode("?", $x);
  7. $url_part = $url_data[0];
  8. $query_part = "";
  9. $query_parms = array();
  10.  
  11. if(count($url_data) > 1){
  12. $query_part = $url_data[1];
  13. }
  14.  
  15. // parse url part
  16. $temp_url_parts = explode("/", $url_part);
  17. $controller = "";
  18. $action = "";
  19. $id = "";
  20. if (count($temp_url_parts) ){
  21. $controller = $temp_url_parts[0];
  22.  
  23. if (count($temp_url_parts) > 1){
  24. $action = $temp_url_parts[1];
  25. }
  26.  
  27. if (count($temp_url_parts) > 2){
  28. $id = $temp_url_parts[2];
  29. }
  30. }
  31.  
  32. // parse query params
  33. if (count($url_data) > 1){
  34. $query_part = $url_data[1];
  35.  
  36. $temp_query_parts = explode("&", $query_part);
  37. foreach($temp_query_parts as $q){
  38. $temp = explode("=", $q);
  39. $key = $temp[0];
  40. $value = $temp[1];
  41. $query_parms[$key] = $value;
  42. }
  43. }
  44.  
  45. $parms = array(
  46. "controller" => $controller,
  47. "action" => $action,
  48. "id" => $id,
  49. "get" => $query_parms,
  50. "post" => $_POST
  51. );
  52.  
  53. print_r($parms);
  54. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.