Reputation: 147
I want to write a PHP code which checks whether a variable contains only letters NOT characters not numbers, I have typed this but it's not working:
$myVar = "Var#iable5";
ereg(^[a-zA-Z] , $myVar)
Upvotes: 1
Views: 22185
Reputation: 7552
PHP has a built in function to do that: ctype_alpha
$myVar = "Var#iable5";
var_dump (ctype_alpha($myVar)); // false
From the docs:
Checks if all of the characters in the provided string, text, are alphabetic. In the standard C locale letters are just [A-Za-z] and ctype_alpha() is equivalent to (ctype_upper($text) || ctype_lower($text)) if $text is just a single character, but other languages have letters that are considered neither upper nor lower case.
Upvotes: 1
Reputation: 360592
Start by not using ereg(). That's been deprecrated for literally years, and WILL be removed from PHP at some point. Plus, your pattern is incorrect. ^
as you're using it is a pattern anchor, signifying "start of line".
You want:
preg_match('/[^a-zA-Z]/', $myVar)
instead. As the first char inside a []
group, ^
means "Not", so "NOT a-zA-Z", not "[a-zA-Z] at start of line" as you were trying.
Upvotes: 1