How to Check if a Variable Includes a Number

July 17, 2013 Development, PHP

How to Check if a Variable Includes a Number

For spam checking in an email script, I wanted to see if the name field had any numbers in it. Spammers write code that automatically fills out contact forms and will add random numbers to the first or last name fields.

To find my answer, I turned to Stack Overflow where Martin Geisler posted a simple solution using a couple PHP functions.

PHP

$name = $_POST['name'];
if(strcspn($name, '0123456789') != strlen($name))
{
     // Add to error array for printing
     $errors[] = 'There has been an error with your submission.'; 
}

Using the strcspn() function, we specify all possible numbers (0-9) as our mask which will be used as a stopping point in finding the length.

For example, if Rob123ert was our string, strcpsn() would return 3 since it finds a number as the fourth character. The strlen() function would return 9 in this example. If these two functions don’t produce equal results, there must be a number in our field.

The sister function of strcspn() is the strspn() function which returns the total number of characters matching the mask, starting from the beginning. For example, if “10395Robert” was our string, the strspn() function would return 5 since the sixth character is a letter.

Tomalak also pointed out that regex, or regular expressions, can be used. Using a pattern of \d which represents a single digit, regex is able to search our $name variable for a match. If one is returned, the result will be greater than 0.

PHP

if(preg_match("/\d/", $name) > 0)
{
     $errors[] = 'Uh-oh! You may be a spammer!';
}

Personally, I prefer the first approach instead of regex since I like to reserve regex for more complicated searches. Regular expression matching can be very powerful, capable of finding nearly anything, but it can also be very inefficient to execute with so much under the hood.

The technique of combining the uncommon strcspn() function and the very common strlen() function is not only easy but also very efficient.

Let's Talk About Your New Website

View Portfolio Contact Today