Check if a string contains any number

This tutorial will discuss about a unique way to check if a string contains any number.

Suppose we have a string and it contains certain letters, special character and numbers. Like this,

$strValue = "Sample 35 Text!";

Now we want to make sure that string contains at least a number in it. For that we are going to use the regular expression.

PHP provides a function preg_match(), and it accepts a regex pattern as the first argument and a string as the second argument. It returns 1, if the given string matches the given regex pattern.

Now, to check if a string contains a number at any place, we can use this regex pattern,

'/\d/'

So we will pass the savings pattern along with the string in that preg_match() function and if string contains at least a number somewhere in it then it will return 1. Otherwise it will return 0.
Like in the below example we have a string and we want to check if it contains a number in it.

Let’s see the complete example,

<?php
/**
 * Checks if a string contains any number using
 * regular expressions (preg_match()).
 *
 * @param string $str The string to check.
 * @return bool True if the string contains any number, false otherwise.
 */
function containsNumber($str)
{
    return preg_match('/\d/', $str) === 1;
}

$strValue = "Sample 35 Text!";

// Check if string contain any numeric value
if (containsNumber($strValue)) {
    echo "The string contains a number.";
} else {
    echo "The string does not contain any number.";
}
?>

Output

The string contains a number.

Summary

We learned how to check if a string contains any number in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top