How to use Regular Expressions In PHP

Regular expressions provide a powerful way to validate and manipulate strings. The preg_match() function can be used to check if a string contains only numeric digits.

Example: This example illustrates checking if string contains only numeric digits using the Regular Expressions.

PHP
<?php

function isNumeric($str)
{
    return preg_match('/^[0-9]+$/', $str);
}

// Driver code
$str1 = "12345";
$str2 = "abc123";

echo isNumeric($str1) ? "Numeric String" : "Non Numeric String";
echo "\n";
echo isNumeric($str2) ? "Numeric String" : "Non Numeric String";

?>

Output
Numeric String
Non Numeric String

How to check if string contains only numeric digits in PHP ?

Given a string, the task is to check whether the string contains only numeric digits in PHP. It is a common task to verify whether a given string consists of only numeric digits in PHP. It can be useful when dealing with user input validation, form submissions, or data processing tasks where numeric values are expected.

For instance, the below examples illustrate the concept:

Input: str = "1234"
Output: true

Input: str = "w3wiki2020"
Output: false

Here, we will cover three common scenarios for checking if the string contains only numeric digits.

Table of Content

  • Using ctype_digit Function
  • Using Regular Expressions
  • Using is_numeric Function
  • Using filter_var Function

Similar Reads

Using ctype_digit Function

PHP provides a built-in function called ctype_digit() that can be used to check if all characters in a string are numeric digits....

Using Regular Expressions

Regular expressions provide a powerful way to validate and manipulate strings. The preg_match() function can be used to check if a string contains only numeric digits....

Using is_numeric Function

The is_numeric() function in PHP checks if a variable is a numeric value or a numeric string....

Using filter_var Function

The filter_var() function in PHP can be used with the FILTER_VALIDATE_INT filter to check if a string contains only numeric digits. This method converts the string to an integer and validates it....

Contact Us