使用正则表达式验证类/方法名称 [英] Validate class/method names with regex

查看:92
本文介绍了使用正则表达式验证类/方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为一家公司使用MVC样式框架,并且出于安全原因,我需要确保通过查询字符串传递的控制器/方法是RFC的有效字符(我找不到)

I'm currently working on an MVC Style framework for a company and for security reasons I need to make sure that the controller / method that's passed via the Query String is valid chars to the RFC (which I can't find).

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

I need to be able to validate / sanitize class names according to what's allowed by the PHP interpreter

例如:

class SomEFunk__YClAssName extends Controller
{

}

我需要某种正则表达式来验证SomEFunk__YClAssName并在需要时对其进行清理!这也是与方法相同的原理.

I need some kind of regex that will validate SomEFunk__YClAssName and sanitize it if need be! This is also the same principles as methods.

有一些事情要考虑,例如

There is a few things to take into consideration such as

  • 开头的数字
  • 仅允许使用下划线
  • 允许使用某些PHP特殊字符.

有关此表达式或可能的表达式的任何信息都将非常有帮助.

Any information on this or possible expressions would be really helpful.

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

Here is some of my Router Code so you can see where I need to implement it:

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;
    }

您将在需要检查的地方看到注释消毒".

You will see the comment "Sanitize" where the check is needed.

推荐答案

我相信您要查找的正则表达式是:

I believe the regex you're looking for is:

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

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

这篇关于使用正则表达式验证类/方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆