用于改变URL的PHP​​交换机案例

I'm building a site on the CodeIgniter framework and I'm using PHP switch to load the specific javascript relevant to the page. My issue comes when I get to the 3rd URI segment, which is generally a variable. for instance I have no issue with say

case 'foo/bar':

but what if my url was something like http://mysite.com/foo/bar/1234, where the 1234 if a variable passed to the controller. It obviously wouldn't make sense to write out a case for every single variable because there's about 30k right now.

currently here's a working snippet of my code...

switch( $this->uri->uri_string() ) {

            case '': 

            break;

            case 'browse':

            break;

            case 'contest/leaderboard':

You could also explode the url on the forward slash and then check each element of an array.

for example

$url_parts = explode('/', $this->uri->uri_string());
switch($url_parts[0]){
  case 'foo':
     if(count($url_parts) > 1){
       if($url_parts[1] == "bar"){
         // when the url begins with foo/bar
       }
     }
     break;
   case 'browse':
     //when url is browse
   break;
}

The benefit of this is you could include code common to all urls that begin with foo. Not sure if this is required but could be useful possibly

So then you use "starts with" conditions:

$uri = $this->uri->uri_string();
if (0 === strpos($uri, 'foo/bar')) {
    // starts with foo/bar
} elseif (0 == strpos($uri, .... etc