2012-05-30 201 views
2

我有如下代碼,這讓$_GET和控制器,動作做除法,而params友好的URL與 「:」

http://localhost/controller/action/param1/param2 

$url = explode('/', $_GET['url']); 
$urlSize = count($url); 
$filter = $this->factory('Core\Security\Filter'); 

if($urlSize >= 1) { 
    $controller = $filter->replace($url[0], 'friendly-url'); 

    if($urlSize >= 2) { 
     $action = $filter->replace($url[1], 'friendly-url'); 

     if($urlSize >= 3) { 
      unset($url[0], $url[1]); 

      foreach($url as $index => $param) { 
       $params[] = $filter->replace($param, 'friendly-url'); 
      } 
     } 
    } 
} 

Core\Security\Filter->replace()這我現在正在開發:

public function replace($data = null, $type = 'alphanumeric') { 
    /* 
     @TODO, implement regex by type 

     numeric 
       $regex = '/^[[:digit:]]$/'; 
     alphanumeric 
       $regex = '/^[[:alnum:]]$/'; 
     friendly-url 
       $regex = '/[^a-zA-Z0-9_-]+/'; 
       $replace = '-' 
     username 
       $regex = '/^[^a-zA-Z0-9_-.]{3,32}+'; 
     email 
       $regex = '/^[[a-zA-Z0-9_-.]{1,96}][email protected][a-zA-Z0-9-]{2,64}+(?:\.[a-zA-Z0-9-]+)*$/'; 
    */ 
} 

好,我的問題是:如何獲得這種格式的網址:

http://localhost/controller/action/param1/param2:value2 

$參數數組:

Array(
    [0] => param1 
    [1] => Array(
     [param2] => value2 
    ) 
) 

解決這一點:在上面使用

foreach($url as $index => $param) { 
    if(strstr($param, ':')) { 
     $subParam = explode(':', $param, 2); 
     $this->_request['params'][][$subParam[0]] = $filter->replace($subParam[1], 'friendly-url-param'); 
    } else { 
     $this->_request['params'][] = $filter->replace($param, 'friendly-url-param'); 
    } 
} 
+1

拜託糖'filter_var($海峽,FILTER_VALIDATE_EMAIL )'而不是一個正則表達式不匹配一大堆有效的ema il地址,已被[覆蓋]的主題(http://stackoverflow.com/questions/201323)[這裏](http://stackoverflow.com/questions/1903356)[at](http:// stackoverflow。 com/questions/703060)[長度](http://stackoverflow.com/questions/997078) – DaveRandom

+1

被警告:URI中的冒號[在Windows apache中不允許](https://issues.apache.org/bugzilla/show_bug的CGI?ID = 41441)。因此,最好避免PHP應用程序中的URL冒號。 –

+0

其中一個要求不是Windows服務器;) –

回答

2
<?php 

$url = 'http://localhost/controller/action/param1/param2:value2'; 

$parts = parse_url($url); 
$path = $parts['path']; 

list($controller, $action, $params) = explode('/', ltrim($path, '/'), 3); 

function parse_params($params) { 
    $parsed_params = array(); 
    $path_segments = explode('/', $params); 
    foreach ($path_segments as $path_segment) { 
     if (strstr($path_segment, ':')) { 
      list($k, $v) = explode(':', $path_segment, 2); 
      $parsed_params[] = array($k => $v); 
     } else { 
      $parsed_params[] = $path_segment; 
     } 
    } 
    return $parsed_params; 
} 



$params = parse_params($params); 

print_r($params); 

輸出

Array 
(
    [0] => param1 
    [1] => Array 
     (
      [param2] => value2 
     ) 

) 
+0

REGEX可能不會完成這項工作。但是,根據您的回答,我已經通過更新後的問題解決了我的問題。謝謝! –