使用regex验证类/方法名称

时间:2010-07-07 14:16:55

标签: php regex object methods

我目前正在为公司制作MVC Style框架,出于安全考虑,我需要确保通过查询字符串传递的控制器/方法是RFC的有效字符(我找不到)

我需要能够根据PHP解释器允许的内容来验证/清理类名

例如:

class SomEFunk__YClAssName extends Controller
{

}

我需要一些可以验证SomEFunk__YClAssName的正则表达式,并在必要时对其进行清理!这也与方法原理相同。

有几件事需要考虑,例如

  • 数字开头
  • 只允许下划线
  • 允许使用某些PHP特殊字符。

关于这个或可能表达的任何信息都会非常有用。

这是我的一些路由器代码,因此您可以看到我需要实现它的位置:

private function prepareQueryString()
    {
        if(strlen($this->query_string) == 0)
        {
            return;
        }
        //Remove [ending|starting|multiple] slashes
        $this->query_string = preg_replace('/^\/+|\/+$|\/(?=\/)/', '', $this->query_string);
        foreach(explode('/',$this->query_string) as $Key => $Value)
        {
            if($Key == 0)
            {
                $Controller = $this->AssignController($Value);
            }
            if($Key == 1)
            {
                $this->AssignMethod($Value);
            }else
            {
                $this->AssignParam($Value);
            }
        }

        //Build RouterVar stdClass
    }

    public function AssignController(String $Controller)
    {
        if(!empty($Controller))
        {
            //Sanitize
        }
    }

    public function AssignMethod(String $Method)
    {
        if(!empty($Method))
        {
            //Sanitize
        }
    }

    public function AssignParam(String $Param)
    {
        $this->params[] = $Param;
    }

您将看到需要检查的评论“Sanitize”。

2 个答案:

答案 0 :(得分:18)

我相信你正在寻找的正则表达式是:

<?php
preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $input);
?>

根据:http://php.net/manual/en/language.oop5.basic.php

答案 1 :(得分:6)

最好使用非常通用的正则表达式,然后通过简单调用class_exists()来测试该类是否存在。

这将匹配任何有效的PHP类名称,包括____3等非常奇怪的名称,这两个名称都是有效的类名称:

/^[a-z_]\w+$/i

我个人比PHP的类命名约定更具限制性。我要求我的控制器大写,并使用_controller进行后期修复,以便不会通过奇怪的URL调用奇怪的非控制器类。我会用这样的东西:

class Products_controller extends Controller { }

// elsewhere, after parsing the controller name from the URI:

if (preg_match('/^[A-Z]\w+_controller$/', $controller_name)
&&  class_exists($controller_name)) {
  $controller = new $controller_name();
}

顺便说一句,通过查询字符串传递控制器名称会产生非常丑陋且搜索引擎不友好的URL。考虑在URL中构建控制器名称和方法:

/products/index # controller=products, action=index
/users/show/3   # controller=users, action=show, user id=3