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

Home > Code Snippets > Verify using ereg that characters in a variable only contain numbers

Verify using ereg that characters in a variable only contain numbers

Description

This function will check a characters in a variable to see if there are any forbidden characters in it. It will make sure that the string only contains numbers, it will not allow letters, only numeric characters. This could be used in a form where visitors have to enter numeric characters, for example you could verify a credit card field.

The code


<?php


// Example 1

$text "012345";

if (
ereg('[^0-9]'$text)) {
  echo 
"This contains characters other than just numbers";
}
else {
  echo 
"This contains only numbers";    
}

// Example 2

$text "mixedcharacters012345&../@";

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

?>

Get the code

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


?>