filter_var using FILTER_VALIDATE_REGEXP

27,141

The regexp should be in an options array.

$string = "Match this string";

var_dump(
    filter_var(
        $string, 
        FILTER_VALIDATE_REGEXP,
        array(
             "options" => array("regexp"=>"/^M(.*)/")
        )
    )
); // <-- look here

Also, the

$namefields = '/[a-zA-Z\s]/';

should be rather

$namefields = '/[a-zA-Z\s]*/'; // alpha, space or empty string

or

$namefields = '/[a-zA-Z\s]+/'; // alpha or spaces, at least 1 char

because with the first version I think you match only single-character strings

Share:
27,141
Iris
Author by

Iris

Web Developer

Updated on April 11, 2020

Comments

  • Iris
    Iris about 4 years

    I'm practicing my beginner php skills and would like to know why this script always returns FALSE?

    What am i doing wrong?

    $namefields = '/[a-zA-Z\s]/';
    
    $value = 'john';
    
    if (!filter_var($value,FILTER_VALIDATE_REGEXP,$namefields)){
        $message = 'wrong';
        echo $message;
    }else{
        $message = 'correct';
        echo $message;
    }
    
    • Iris
      Iris about 12 years
      When I use preg_match() instead it works fine...
    • Anthony Rutledge
      Anthony Rutledge over 9 years
      preg_match() would require you to use a callback filter. If you want to use the PHP filter mechanism (which is operating a bit differently than using superglobals), just create an associative array like in the manual examples.
    • Cyclonecode
      Cyclonecode over 5 years
      Why don't people read the documentation?
  • Iris
    Iris about 12 years
    Really? That's not very clear from the documentation in the php manual :-/ Thanks also for the regex tips :) I'll fiddle around with this a bit.
  • Cranio
    Cranio about 12 years
    For regular expressions in general, and in PHP, you may give a look to: regular-expressions.info/tutorial.html and regular-expressions.info/php.html this site helped me a lot.