Check if a String Contains Only Numbers in PHP

This tutorial will discuss about a unique way to check if a string contains only numbers in php.

Suppose we have a string now we want to check that string contain only numbers it can be an integer or it can be a double value

For that we can use the regular expression with following regex pattern,

'/^[+-]?\d+(\.\d+)?$/'

The regex pattern matches a string that contains a number only. It can be an integer or a double value, it matches in both the cases.

We have created a function that accepts a string as an argument and returns true if the given string is a number i.e.

function containsOnlyNumbers($str)
{
    $pattern = '/^[+-]?\d+(\.\d+)?$/';
    return preg_match($pattern, $str) === 1;
}

Inside this function ,we are going to use the preg_match() function. In this function we will pass their regex pattern as the first argument and string as a second argument. If it returns 1, then it means that the given string contains the number only.

Example 1: in which we will check that string “56” contains a number only.

Let’s see the complete example,

<?php
/**
 * Checks if a string contains only numbers using
 * regular expressions (preg_match()).
 *
 * @param string $str The string to check.
 * @return bool True if the string contains only numbers, false otherwise.
 */
function containsOnlyNumbers($str)
{
    $pattern = '/^[+-]?\d+(\.\d+)?$/';
    return preg_match($pattern, $str) === 1;
}

$strValue = "56";

// Check if string contains only numbers
if (containsOnlyNumbers($strValue)) {
    echo "The string contains only numbers.";
} else {
    echo "The string does not contain only numbers.";
}
?>

Output

The string contains only numbers.

Example 2: Check if string contains double or float number

In this example, we have a string that contains a double value. Now we will check if the string contains a number or not.

Let’s see the complete example,

<?php

function containsOnlyNumbers($str)
{
    $pattern = '/^[+-]?\d+(\.\d+)?$/';
    return preg_match($pattern, $str) === 1;
}


$strValue = "123.89";

// Check if string contains only numbers
if (containsOnlyNumbers($strValue)) {
    echo "The string contains only numbers.";
} else {
    echo "The string does not contain only numbers.";
}
?>

Output

The string contains only numbers.

Summary

We learned about a way to check if string contains only 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