Check if String contains Numbers in PHP

This tutorial will discuss how to check if string contains numbers in PHP.

To check if a string contains at least one number in PHP, we can utilize regular expressions.

The regex pattern that we can use is as follows,

'/[0-9]/'

By passing this regex pattern and the string to the preg_match() function, we can determine if the given string contains at least one number. If preg_match() returns 1, it means that the string contains a digit.

We have created a separate function,

function hasNumbers($strValue)
{
    return preg_match('/[0-9]/', $strValue) === 1;
}

It accepts a string as an argument and returns true if the string contains at least one number. The function internally uses the preg_match() function with the provided regex pattern to perform the check.

Let’s see the complete example,

<?php
/**
 * Check if a string contains atleast few numbers in it.
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string contains numbers,
 *              False otherwise.
 */
function hasNumbers($strValue)
{
    return preg_match('/[0-9]/', $strValue) === 1;
}

$strValue = 'This is a Random number 56 today.';

// Check if string contains few numbers in it
if (hasNumbers($strValue)) {
    echo "The string contains numbers.";
} else {
    echo "The string does not contain numbers.";
}
?>

Output

The string contains numbers.

Summary

Today, we learned how to check if string contains numbers 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