How to check characters in a string are alphanumeric in php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to check characters in a string are alphanumeric in php

Post by Saman » Fri Jul 15, 2011 6:16 pm

This verifies if a PHP 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.

Code: Select all

<?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";     
} 

?>
Post Reply

Return to “PHP & MySQL”