1

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)
Montoolivo
  • 137
  • 2
  • 3
  • 15
  • 6
    Sidenote: [`ereg()`](http://php.net/manual/en/function.ereg.php) is deprecated. *"This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged."* – Funk Forty Niner Sep 02 '14 at 17:17
  • 1
    Could you define "letter" as opposed to "character"? Is é a letter? Is ∑? – Matt Gibson Sep 02 '14 at 17:20
  • 1
    @mattgibson -- or what about good old ß? – Anthony Sep 02 '14 at 17:28
  • Letter is A , B , C .... Characters # , ! , "" , ^ – Montoolivo Sep 02 '14 at 17:30
  • I can't tell from your response whether é, ß, ∑, etc.—perfectly normal, extremely common letters in a variety of languages, just like A B or C—should count or not. Perhaps you could tell us why you want to do this? It might help us to understand the requirements better. – Matt Gibson Sep 02 '14 at 19:04

3 Answers3

14

No need for regex:

$result = ctype_alpha($myVar);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
1

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

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.

hlscalon
  • 7,304
  • 4
  • 33
  • 40