Reputation:
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
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