How to filter or sanitize numbers from strings in PHP?
In this article, we discuss, how to extract or filter out numbers from a string in PHP.
There are various ways to do this, some prefer way we are discussing bellow
Table of content:
- Method 1: Using filter_var() Function.
- Method 2: Using preg_replace() function.
- Method 3: Using preg_match_all() Function.
Method 1: Using filter_var() Function.
The filter_var() function filters a variable with the specified filter and also sanitizes the data.
Syntax:
filter_var(var, filtername, options)
Return Value: It returns the filtered data on success, or FALSE on failure.
Example:
<?php
$str = 'Welcome 2 bootstrapfriendly 2020';
// Filter the Numbers from String
$int_var = (int)filter_var($str, FILTER_SANITIZE_NUMBER_INT);
// print output of function
echo "The numbers are:". $int_var;
?>
The output of the above code is: 22020
Method 2: Using preg_replace() function.
The preg_replace() PHP function is an inbuilt function in PHP that is used to perform a regular expression for search and replace the content. where all matches of a pattern or list of patterns found in the input are replaced with substrings.
Syntax:
preg_replace($patterns, $replacements, $input, $limit, $count)
Return Value: This function returns an array if the input parameter is an array, otherwise it will return a string.
<?php
// Declare a variable
$str = 'Welcome 2 bootstrapfriendly 123';
// Filter the Numbers from String
$int_var = preg_replace('/[^0-9]/', '', $str);
// print output of function
echo "The numbers are:". $int_var;
?>
The output of the above code is: 2123
Method 3: Using preg_match_all() Function.
The preg_match() function is used to search a specific string or extract numbers from a string. Usually, the search starts from the starting of the input string. The optional parameter offset is used to specify the position from where to start the search.
Return:
The preg_match() function returns where a match was found in a string.
Syntax:
int preg_match( $pattern, $input, $matches, $flags, $offset )
Example:
<?php
// Declare a variable
$str = 'Welcome 2 bootstrapfriendly 123';
// Use preg_match_all() function to check match
preg_match_all('!\d+!', $str, $matches);
// print output of function
print_r($matches);
?>
The output of the above code is :
Array ( [0] => Array ( [0] => 2 [1] => 123 ) )