Regx.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Qii\Route\Parse;
  3. /**
  4. * Route规则 支持正则表达式
  5. *
  6. * @author Jinhui Zhu<jinhui.zhu@live.cn>2015-10-24 23:11
  7. * @version 1.2
  8. */
  9. class Regx
  10. {
  11. const VERSION = '1.2';
  12. private $config;
  13. public function __construct()
  14. {
  15. }
  16. public function setConfig($config)
  17. {
  18. $this->config = $config;
  19. }
  20. /**
  21. * 匹配路由
  22. * @param String $controller 控制器名称
  23. * @param String $action 动作名称
  24. *
  25. * 支持规则:controller/(:any) controller/(:num) controller/(.*) 等一系列正则规则
  26. */
  27. public function parse($controller, $action)
  28. {
  29. $uri = $controller . '/' . $action;
  30. foreach ($this->config AS $key => $val) {
  31. $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));
  32. // Does the RegEx match?
  33. if (preg_match('#^' . $key . '$#', $uri)) {
  34. // Do we have a back-reference?
  35. if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE) {
  36. $val = preg_replace('#^' . $key . '$#', $val, $uri);
  37. }
  38. $router = explode('/', $val);
  39. return array('controller' => $router[0], 'action' => $router[1]);
  40. }
  41. }
  42. return array('controller' => $controller, 'action' => $action);
  43. }
  44. }
  45. ?>