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

Home > Code Snippets > Check that characters in a variable are alpha numeric using ereg

Check that characters in a variable are alpha numeric using ereg

Description

This verifies if a PHP variable string contains characters other than letters or numbers using the PHP function ereg. This PHP code snippet can be useful for form input where you only want users to input alpha numeric characters.

The code


<?php


// Example 1

$text "onlyalphanumericcharacters012345";

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

// Example 2

$text "mixedcharacters012345&../@";

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

?>

Get the code

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