简体   繁体   English

PHP开关盒,用于不同的URL

[英]PHP switch case for varying url

I'm building a site on the CodeIgniter framework and I'm using PHP switch to load the specific javascript relevant to the page. 我正在CodeIgniter框架上构建站点,并且正在使用PHP开关加载与页面相关的特定javascript。 My issue comes when I get to the 3rd URI segment, which is generally a variable. 我遇到的问题是当我到达第3个URI段时,该段通常是一个变量。 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. 但是,如果我的网址是http://mysite.com/foo/bar/1234之类的 ,那么将1234(如果变量传递给控制器​​)​​呢? It obviously wouldn't make sense to write out a case for every single variable because there's about 30k right now. 为每个变量写一个案例显然是没有道理的,因为现在大约有30k。

currently here's a working snippet of my code... 目前,这是我的代码的有效代码段...

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

            case '': 

            break;

            case 'browse':

            break;

            case 'contest/leaderboard':

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

You could also explode the url on the forward slash and then check each element of an array. 您还可以将正斜杠上的URL展开,然后检查数组的每个元素。

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. 这样做的好处是您可以包含所有以foo开头的url通用的代码。 Not sure if this is required but could be useful possibly 不知道这是否是必需的,但可能有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM