Looking for somewhere to host your site? Browse our PHP web hosts section!

Home > Code Snippets > Use ereg to check that characters in a variable only contain letters

Use ereg to check that characters in a variable only contain letters

Description

If you want to verify a PHP variable to make sure there are only lower case and upper case letters in it then this will do the job. An example use of this code could be in a form field, to check a username is only alpha characters.

The code


<?php


// Example 1

$text "onlytextcharacters";

if (
ereg('[^A-Za-z]'$text)) {
  echo 
"This contains characters other than just letters";
}
else {
  echo 
"This contains only letters";    
}

// Example 2

$text "mixedcharacters012*&.@";

if (
ereg('[^A-Za-z]'$text)) {
  echo 
"This contains characters other than just letters";
}
else {
  echo 
"This contains only letters";    
}

?>

Get the code

Download the file to your computer: Click here to get the file