user5820249
user5820249

Reputation:

PHP preg_match return false even if condition match

I am using preg_match to verify an input :

$string = 'test';

if (preg_match ('/[^-a-z\d]/i', $string))
{
    return true;
}
else
{
    return false;
}

Well I can not understand why it return false here !

Am I missing something ?

Shouldn't it return true ?

The solution :

(preg_match ('/^[-a-z\d]*$/i', $string))

Upvotes: 1

Views: 3814

Answers (2)

Jignesh Patel
Jignesh Patel

Reputation: 1022

Tyr this

(preg_match ('/^[-A-Za-z\d]*$/', $string))

Upvotes: 2

Mikey
Mikey

Reputation: 2704

So preg_match() can return 0, 1, or false it is probably safer to do a strict check that the result equals 1, i.e.

abstract class Pattern 
{
    /** @const int */
    const TEXT_MATCH = 1;

    /**
     * @param string $pattern regex pattern to match against
     * @param string $string  the text string to search
     * 
     * @return bool 
     */
    public static function match(string $pattern, string $string): bool
    {
        return preg_match($pattern, $string) === self::TEXT_MATCH;
    }
}

Primarily the bit you're interested in is this

preg_match($pattern, $string) === 1;

If you then use it:

$result = Pattern::match('/[^-a-z\d]/i', 'test');
var_dump($result); // false

The string doesn't pass the check. If that doesn't resolve your issue we're going to need to see a few examples of strings you are passing through that are always passing. It's probably also worth explaining what you want the regex to match against, because that could be part of the issue also.

Upvotes: 1

Related Questions