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
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
Contact Us