preg_match_all(): Delimiter must not be alphanumeric or backslash

Asked

Viewed 264 times

2

class Check {

    private static $Data;
    private static $Format;

    public static function Email($Email) {
        self::$Data = (string) $Email;
        self::$Format = "/[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\.\-]+\.[a-z]{2,4}$/";

        if (preg_match(self::$Data, self::$Format)):
            return true;
        else:
            return false;
        endif;
    }

}

Above my code where I use, the pre_match is making a mistake:

Delimiter must not be alphanumeric or backslash

I looked into it, but I couldn’t fix it. What I’m doing wrong ?

  • what the input data?

  • email [email protected] , in case $Data is receiving this email.

  • can’t help you, but for email validation I usually use filter_input($string, FILTER_VALIDATE_EMAIL)

  • thanks, I got it with your tip ;)

1 answer

6

You are reversing the parameters, a read on manual avoids these problems.

preg_match ( string $pattern , string $subject )

The correct order would be this:

 preg_match(self::$Format,self::$Data)

This doesn’t make much sense:

if (preg_match(self::$Data, self::$Format)):
    return true;
else:
    return false;
endif;

If it’s to return true or false already return the value directly, there is no reason to if.

class Check {

    private static $Data;
    private static $Format;

    public static function Email($Email) {
        self::$Data = (string) $Email;
        self::$Format = "/[a-z0-9_\.\-]+@[a-z0-9_\.\-]*[a-z0-9_\.\-]+\.[a-z]{2,4}$/";

        return preg_match(self::$Format,self::$Data);
    }
}

It is also worth saying that the variables in this case could be local (only of the method, and not of the class).

As Rafael mentioned in the comments, if you prefer PHP you already have an alternative ready for this, which is recommended in place of your Regex (which by the way does not respect the valid standard of emails, denying things you should not).

filter_input($string, FILTER_VALIDATE_EMAIL) 
  • Bacco Thanks for the lesson, really you are right, I did not heed the basic reading. And my if there was no need, man, thank you even. : D

  • 3

    @Diegogo always get used to seeing the PHP manual, which avoids these problems and you don’t get hurt depending on the luck of someone responding when you need it. Since PHP has a very strange order of parameters, even those who have experience need to "take the web out" once in a while. We’re here to help, but the more you can handle these things on your own, the less time you get stuck in problems like this. But when you need it, ask, of course.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.