URL的路由参数的正则表达式

时间:2015-01-07 12:11:25

标签: php regex kohana

我对正则表达式不太满意,这就是为什么我需要你的帮助。 看这里http://kohanaframework.org/3.3/guide/kohana/routing#examples

Route::set('search', ':<query>', array('query' => '.*'))
  ->defaults(array(
    'controller' => 'Search',
    'action' => 'index',
  ));

这个正则表达式(.*)除了我需要的所有参数外:
&#34; cat1/cat2/cat3&#34;
还有:
&#34; cat1/cat 2/ cat3&#34 ;,
&#34; cat1/cat 2/ /// a |<>"?\':*&#34;
如何修改此表达式以禁止:
1.任何类型的空间(&#34; \s&#34;)
2.多一个斜线(&#39; cat1/cat2&#39;但不是&#39; cat1/////cat2&#39;)
3.以及范围的每个符号:["|", "<", ">" , "\"", "?", "\", "'", ":", "*"]

感谢所有试图帮助我的人

define('CATEGORIES_RGXP', '(?:[^|<>\\?"\':*\s]+\/?)+');
Route::set('debug_route', '(<categories>/)<file>.<ext>',array(
    'categories'    => CATEGORIES_RGXP,
))
    ->defaults(array(
        'controller'        =>  'index',
        'action'            =>  'file',
    ));

当我按照&#34; / cat1 / cat2 /////cat3 / file.php&#34;:var_dump($this->request->param());

时转储到控制器中
array(3) {
  ["categories"]=>
  string(14) "cat1/cat2/cat3"
  ["file"]=>
  string(4) "file"
  ["ext"]=>
  string(3) "php"
}

所以它允许传递一组斜线

1 个答案:

答案 0 :(得分:3)

.匹配解释观察到的行为的每个字符(新行除外)

相反,我们会使用否定的字符类,即[^X],这意味着&#34;匹配所有 X&#34;

根据您的要求,您应该使用:

^((?:[^|<>\\\/?"':*\s]+\/?)+)$

DEMO

  NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    (?:                      group, but do not capture (1 or more
                             times (matching the most amount
                             possible)):
--------------------------------------------------------------------------------
      [^|<>\\\/?"':*\s         any character except: '|', '<', '>',
      ]+                       '\\', '\/', '?', '"', ''', ':', '*',
                               whitespace (\n, \r, \t, \f, and " ")
                               (1 or more times (matching the most
                               amount possible))
--------------------------------------------------------------------------------
      \/?                      '/' (optional (matching the most
                               amount possible))
--------------------------------------------------------------------------------
    )+                       end of grouping
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string