Reputation: 2205
i have the following php code for validate First Name, Last Name
if (preg_match("/^[A-Za-z\p{Greek}\s]+$/u", "Hello & World!", $m))
{
//validation pass
echo "validation pass";
}
else
{
//validation failed
var_dump($m);
echo "validation failed";
}
The problem is that i was expecting on $m[0] to found the non matching elements so echo a message like
echo "{$m[0]} is not allow character(s)";
but the $m variable is an empty array
Any help appreciated Thanks
Upvotes: 2
Views: 377
Reputation: 626929
You can't do that with a single regex, as the non-matching chars are not stored after a match is failed.
You may use a kind of an inverted pattern after failing a match, like
$s = "Hello & World!";
if (preg_match("/^[A-Za-z\p{Greek}\s]+$/u", $s)) {
echo "validation pass"; //validation pass
}
else {
if (preg_match_all('~[^A-Za-z\p{Greek}\s]~u', $s, $m)) { //validation failed
var_dump($m[0]);
}
echo "validation failed";
}
See the PHP demo. Output:
array(2) {
[0]=>
string(1) "&"
[1]=>
string(1) "!"
}
validation failed
The [^A-Za-z\p{Greek}\s]
pattern is a negated character class matching any char other than the one(s) defined in the class: ASCII and Greek letters and whitespaces.
Upvotes: 1