English 中文(简体)
使用PHP过滤功能,如过滤器_var_array()可以检查,如果输入线的长度低于某些价值。
原标题:Using PHP filter functions like filter_var_array() is there a way to check if length of an input string is less than some value
  • 时间:2009-09-28 20:43:33
  •  标签:

I have been toying with PHP filter library. I liked it but I am unable to perform a simple filter function. I essentially want to invalidate those values in my input array that are strings and which are longer than certain value. Is there a way to do this like,

$data = array( input_string_array  => array( aaa ,  abaa ,  abaca ));
$args = array(
     component     => array( filter     => FILTER_DEFAULT,
                             flags      => FILTER_REQUIRE_ARRAY, 
                             options    => array( min_length  => 1,  max_length  => 10)
                           )
);

var_dump(filter_var_array($data, $args));

我曾尝试过这一点,并给我留下错误。 据认为,目前不存在任何min/max/max。 那么,如何执行? 这里还提到了所有此类选择,如“最大”、“min”、“reg”等。

另外,在过滤器中,我还有另一个疑问。 我愿知道,是否有办法将数据以外的参数传递给所谓的功能? 比如,

echo filter_var($string, FILTER_CALLBACK, array("options"=> array("lengthChecker", "5")));

有了很大的帮助。

最佳回答
问题回答

我认为,最初的问题是,数据阵列中的实地名称与过滤阵列中的外地名称不同。

Introduction

您至少需要PHP 5.4+,以便回答工作(至少应归功于各组别)。

如果目标是这样做:

$filteredArray = filter_var_array($arrayToFilter, $filterInstuctionsArray);

......并使用基本住户调查功能(连同决定逻辑)的回报结果来检查舱位的长度(mb_strlen(<>>/code>,strlen(<>),关键在于有精良的过滤指令Array'。 向您的反馈职能提出论据(用于再利用、资本和一般化等), 我认为至少有两种情况。

Scenarios

<>A /object。

 options  => [$this,  callbackMethod ]

 options  => [$this->object,  callbackMethod ]

 options  => [$object,  callbackMethod ]

http://www.ohchr.或g。

 options  =>  callbackFunction 

Solutions

<>1> <><><> >t$thiscode>$object in Options Astrong> with a new instance of an Object right where and there, adopt in any debate its Construction或. 这似乎不太可能,因为它是紧凑的法典的摇篮。

Alternative, one could inject a pre-populated Object into a Validat或 categ或y of some such and pr filter_input_array(>. 因此,通过对<代码>的回顾式样的论点 www.un.或g/spanish/ga/president

<>2>。 rel=“nofollow n或etinger”>PHP 匿名功能,并实施<> > <> > > > > > > > syntax to adoptarguments / restrictions > from thecode>Validat或

function ($value) use ($min, $max) {
    $length = mb_strlen($value,  UTF-8 );
    return ($length >= $min) && ($length <= $max);
}

Attempt #1: Filter Instructions Array with Anonymous Functions

这里是同微量价值一起工作的必然例子。

$filterInstructionsArray[
                             fName  = [ filter   => FILTER_CALLBACK,
                                        flags    => FILTER_REQUIRE_SCALAR,
                                        options  => function ($value) use ($min, $max) {
                                                          $length = mb_strlen($value,  UTF-8 );
                                                          return ($length >= $min) && ($length <= $max);}],
                             lName  = [ filter   => FILTER_CALLBACK,
                                        flags    => FILTER_REQUIRE_SCALAR,
                                        options  => function ($value) use ($min, $max) {
                                                          $length = mb_strlen($value,  UTF-8 );
                                                          return ($length >= $min) && ($length <= $max);}]
                         ];

当然,这违反了<>DRY原则。 因此,你可以将匿名功能界定为<代码>Validat或类别(或仅将其归入变量)的财产,从而使其成为“<代码>的指定例子。 结束

private $checkNameLength = function ($value) use ($this->nameMin, $this->nameMax) {
        $length = mb_strlen($value,  UTF-8 );
        return ($length >= $this->nameMin) && ($length <= $this->nameMax);
    };

$checkNameLength = function ($value) use ($min, $max) {
        $length = mb_strlen($value,  UTF-8 );
        return ($length >= $min) && ($length <= $max);
    };

因此,我希望两件事之一将发挥作用。

Attempt #2: Filter Instructions Array with Named Anonymous Functions

$filterInstructionsArray[
                             fName  = [ filter   => FILTER_CALLBACK,
                                        flags    => FILTER_REQUIRE_SCALAR,
                                        options  => [$this,  checkNameLength ]]
                         ];

$filterInstructionsArray[
                             fName  = [ filter   => FILTER_CALLBACK,
                                        flags    => FILTER_REQUIRE_SCALAR,
                                        options  =>  checkNameLength ]
                         ];

Potential Complications

<代码>Closurease $this->checkNameLength and $checkNameLength arebject, not n或mal“methods /Function”。 但是,如果PHP没有抱怨,我将不分理发。 我恳请大家尝试在匿名职能范围内确定一项职能。

$checkName = function ($value) use ($min, $max) {

        function lengthTest($string, $min, $max){
            $length = mb_strlen($string,  UTF-8 );
            return ($length >= $min) && ($length <= $max);
        }
    };

然后,你的教学过滤阵列会照此办理。

$filterInstructionsArray[
                             fName  = [ filter   => FILTER_CALLBACK,
                                        flags    => FILTER_REQUIRE_SCALAR,
                                        options  => [$checkName,  lengthTest ]]
                         ];

或, probably this ...

$filterInstructionsArray[
                             fName  = [ filter   => FILTER_CALLBACK,
                                        flags    => FILTER_REQUIRE_SCALAR,
                                        options  =>  lengthTest ]
                         ];

Conclusion

采用PHP s/code>和匿名功能,比采用PHP s更能创建通用的长度核对器。 使用<代码>过滤 => FILTER_VALIDATE_REGEXP 能够方便检查单一方位的长短,但这不能取代遵守《南半球原则》。 最后,您将在“this等过滤指示阵列中发表许多声明,只是为了在一系列投入中缩短篇幅。

    //If you just want to test only the lengths first, this is
    //very inefficient. Assume each $regex is only checking string length.

    $filterLengthInstructions = [
                 fName     => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $fNameRegex]],
                 lName     => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $lNameRegex]],
                 company   => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $comanyRegex]],
                 address1  => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $address1Regex]],
                 address2  => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $address2Regex]],
                 zip       => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $zipRegex]],
                 website   => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $urlRegex]],
                 email   => [ filter   => FILTER_VALIDATE_REGEXP,
                                flags    => FILTER_REQUIRE_SCALAR,
                                options  => [ regexp  => $emailRegex]]
     ];

如果你试图做一个<purefilter_input_array(>>>/code/ 但是,您将不得不将 /multiple> 出入filter_var_array(>,并加上多个filter号指令阵列。 (由于体积长度不是使之有效或无效的唯一东西)。

关于<代码>website和email ,您将利用 过滤 => FILTER_VALIDA_URL滤=> FILTER_VALIDATE_EMAIL.。 在其他时候,您将希望利用<代码>过滤 => FILTER_VALIDATE_IP/code>。 此外,特别是在<代码>email的情况下,您可能希望将有效的电子邮件地址限制在正式金融共同体的一个分支,并定期发表讲话。 为了保持纯洁,你不会将这种定期表述列入<条码>。

想修改<代码>min_length <>/code>和max_length的基本原因,是能够一劳永逸地书写业务逻辑。

至少,我的建议是建立一个抽象的<代码>Validat或超级类别,并界定一种(1)方法,用以测试长度。

“Class

现在,你可以把这一方法分割开来,或者把这项任务交给一种注入的<条码> 编码试验器/代码>物体。

“Class

不管怎样,但通过界定具体的儿童类别(<条码>/条码>),你们都必须做的是界定你在一阵列中的测试参数,形成一种 lo,并且呼吁:

$this->testString($string, $min, $max, $pattern, $err或Message);

$this->stringTester->testString($string, $min, $max, $pattern, $err或Message);

... within the loop. Be sure to account f或 the $err或Message.

abstract Class Tester
{

}

class StringTester extends Tester
{
    private function testString($string, $min, $max, $pattern, &$err或Message)
    {
        $length = mb_strlen($string,  UTF-8 );

        if ($length < $min) // Test string against minimum length. {
            $err或Message =  Too small! ( .$min.  min,   .$length.   given.) ;
        }
        elseif ($length > $max) // Test string against maximum length. {
            $err或Message =  Too large! ( .$max.  max,   .$length.   given.) ;
        }
        elseif (preg_match($pattern, $string) === 0) // Test string s pattern. {
            $err或Message =  Invalid string f或mat! ;
        } else {
            $err或Message =   ;  // The err或 message is the empty string.
        }

        return;
    }
}

abstract Class Validat或
{
    // Arrays
    protected $inputArray;
    protected $err或MessagesArray = [];
    protected $stringTestRulesArray;  // I know. I know. :-)

    // Objects
    protected $stringTester;

    // Abstract functions
    abstract public function validate();

    public function __construct(Tester $stringTester, array $inputArray, array $stringTestRutlesArray)
    {
        $this->stringTester = $stringTester;
        $this->inputArray = $inputArray;
        $this->stringTestRulesArray = $stringTestRulesArray
    }

    public function getInput()
    {
        return $this->inputArray;
    }

    public function getErr或Messages()
    {
        return $this->err或MessagesArray();
    }

    protected function validateStrings()
    {
        // Notice how input values c或respond to err或 message elements via $key.
        f或each ($this->stringTestRulesArray as $key = $valuesArr) {           
            $this->stringTester->testString($this->inputArray[$key], $valuesArr[ min ], $valuesArr[ max ], $valuesArr[ pattern ], $this->err或MessagesArray[$key]);
        }

        return;
    }

}

class ContactValidat或 extends Validat或
{
    public function __construct(Tester $stringTester, Sanitizer $sanitizer)
    {
        $stringTestRulesArray = [
                                   fName  => [ min  => 1,  max  => 25,  pattern  =>  /[A-Za-z  -]/ ],
                                   lName  => [ min  => 1,  max  => 40,  pattern  =>  /[A-Za-z  -]/ ]
                                ];

        parent::__construct($stringTester, $sanitizer->getInput(), $stringTestRulesArray);
    }

    public function validate()
    {
        $this->validateStrings();
        //Other, contact f或m specific validation stuff.
    }
}

class RegisterValidat或 extends Validat或
{
    public function __construct(Tester $stringTester, Sanitizer $sanitizer)
    {
        $stringTestRulesArray = [
                                   fName  => [ min  => 1,  max  => 30,  pattern  =>  /[A-Za-z  -]/ ],
                                   lName  => [ min  => 1,  max  => 45,  pattern  =>  /[A-Za-z  -]/ ]
                                ];

        parent::__construct($stringTester, $sanitizer->getInput(), $stringTestRulesArray);
    }

    public function validate()
    {
        $this->validateStrings();
        //Other, register f或m specific validation stuff.
    }
}

有关<代码>的问题第二部分 FILTER_CALLBACK。

在PHP5.4+中,你可以发挥功能,恢复固定功能,作为后备力量。

Example https://3v4l.org/m3isD

我包括一个样本<条码>有效性_length功能,感到可以自由使用你自己的环境卫生或鉴定。 电话:filter_var(美元价值、百分数);

function validate_length($min = 1, $max = null) 
{
    return static function ($value = null) use ($min, $max) {
        $len = strlen($value);
        if (null !== $min && $len < $min) {
           return false;
        }
        if (null !== $max && $len > $max) {
           return false;
        }

        return $value;
    };
}

$_POST = [
    a  =>  value ,
    b  =>   ,
    c  =>  Valid 
];

$result = filter_input_array(INPUT_POST, [
     a  => [ filter  => FILTER_CALLBACK,  options  => validate_length(null, 4)],
     b  => [ filter  => FILTER_CALLBACK,  options  => validate_length(1)],
     c  => [ filter  => FILTER_CALLBACK,  options  => validate_length(1, 10)]
]);

var_dump($result);

<>Result>

array(3) {
  ["a"]=>
  bool(false)
  ["b"]=>
  bool(false)
  ["c"]=>
  string(5) "Valid"
}

如前所述,你可以扩大反馈论点,以接受你想要的参数,并进行更多的过滤。

Example https://3v4l.org/83uXu

function validate_length($options = [ min_length  => 1,  max_length  => null], $filters = null)
{
    return static function ($value = null) use ($options, $filters) {
        $len = strlen($value);
        if (isset($options[ min_length ]) && $len < $options[ min_length ]) {
           return false;
        }
        if (isset($options[ max_length ]) && $len > $options[ max_length ]) {
           return false;
        }
        if (null !== $filters) {
            return filter_var($value, ...$filters); //php 5.6+ array unpacking operator
        }

        return $value;
    };
}

$a = [
    a  =>  value ,
    b  =>   ,
    c  =>  a@example.com ,
    d  =>  This& is a ? Test ,
];

$email_filter = [FILTER_VALIDATE_EMAIL, [ flags  => FILTER_FLAG_EMAIL_UNICODE]];
$string_filter = [FILTER_SANITIZE_STRING, [ flags  => FILTER_FLAG_ENCODE_AMP | FILTER_FLAG_STRIP_HIGH]];

$result = filter_var_array($a, [
     a  => [ filter  => FILTER_CALLBACK,  options  => validate_length([ max_length  => 4])], 
     b  => [ filter  => FILTER_CALLBACK,  options  => validate_length([ min_length  => 1])], 
     c  => [ filter  => FILTER_CALLBACK,  options  => validate_length([ min_length  => 1,  max_length  => 20], $email_filter)],
     d  => [ filter  => FILTER_CALLBACK,  options  => validate_length([ min_length  => 1], $string_filter)],
]);

var_dump($result);

<>Result>

array(4) {
  ["a"]=>
  bool(false)
  ["b"]=>
  bool(false)
  ["c"]=>
  string(13) "a@example.com"
  ["d"]=>
  string(20) "This&#38; is a  Test"
}




相关问题
热门标签