Filter numbers from string php

Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.

filter_var

flags for the filters

e.g. to get just numbers from the given string


To adhere to more strict standards for your question, I have updated my answer to give a better result.

I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.

Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.

Edit:

1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT

2: If you have a PHP version less than 5.4, then kindly use array['+', '-'] instead of the short array syntax ['+', '-'].

  1. HowTo
  2. PHP Howtos
  3. Extract Numbers From a String in PHP

Created: September-22, 2020 | Updated: December-10, 2020

  1. Use preg_match_all[] Function to Extract Numbers From a String in PHP
  2. Use filter_var[] Function to Extract Numbers From a String in PHP
  3. Use preg_replace[] Function to Extract Numbers From a String in PHP

In this article, we will introduce methods to extract numbers from a string in PHP.

  • Using preg_match_all[] function
  • Using filter_variable[] function
  • Using preg_replace[] function

We can use the built-in function preg_match_all[] to extract numbers from a string. This function globally searches a specified pattern from a string. The correct syntax to use this function is as follows:

preg_match_all[$pattern, $inputString, $matches, $flag, $offset];

The built-in function preg_match_all[] has five parameters. The details of its parameters are as follows

ParametersDescription
$pattern mandatory It is the pattern that we want to check in the given string.
$inputString mandatory It is the string for which we want to search the given pattern.
$matches optional If this parameter is given, then the function stores the result of the matching process in it.
$flags optional This parameter has two options: PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL. You can read its description here.
$offset optional It tells the function of where to start the matching process. Usually, the search starts from the beginning.

This function returns a Boolean variable. It returns true if the given pattern exists.

The program below shows how we can use the preg_match_all[] function to extract numbers from a given string.

 

We have used !\d+! pattern to extract numbers from the string.

Output:

Array
[
    [0] => Array
        [
            [0] => 4
            [1] => 6
        ]

]

We can also use the filter_var[] function to extract numbers from a string. The correct syntax to use this function is as follows:

filter_var[$variableName, $filterName, $options]

The function filter_var[] accepts three parameters. The detail of its parameters is as follows

ParametersDescription
$variableName mandatory It is the variable to filter.
$filterName mandatory It is the name of filter which will be applied to the variable. By default, it is FILTER_DEFAULT
$options mandatory This parameter tells about the options to use.

We have used FILTER_SANITIZE_NUMBER_INT filter. The program that extracts numbers from the string is as follows:

 

Output:

The extracted numbers are: 46 

In PHP, we can also use the preg_replace[] function to extract numbers from a string. The correct syntax to use this function is as follows:

preg_replace[$regexPattern, $replacementVar, $original, $limit, $count]

The function preg_replace[] accepts five parameters. The detail of its parameters is as follows

ParametersDescription
$regexPattern mandatory It is the pattern we will search in the original string or array.
$replacementVar mandatory It is the string or array which we use as a replacement for the searched value.
$original mandatory It is the string or an array from which we want to find value and replace it.
$limit optional This parameter limits the number of replacements.
$count optional This parameter tells about the number of total replacements made on our original string or array.

We will use the pattern /[^0-9]/ for finding numbers in the string. The program that extracts numbers from the string is as follows:

 

Output:

The extracted numbers are: 46 

Related Article - PHP String

  • Remove All Spaces Out of a String in PHP
  • Convert DateTime to String in PHP
  • Convert String to Date and Date-Time in PHP
  • Convert an Integer Into a String in PHP
  • How to Extract Numbers From a string PHP?

    Use preg_match_all[] Function to Extract Numbers From a String in PHP..
    Use filter_var[] Function to Extract Numbers From a String in PHP..
    Use preg_replace[] Function to Extract Numbers From a String in PHP..

    How to separate string and number in PHP?

    explode[] is a built in function in PHP used to split a string in different strings. The explode[] function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

    How do I check if a string contains only numbers in PHP?

    The is_numeric[] function checks whether a variable is a number or a numeric string. This function returns true [1] if the variable is a number or a numeric string, otherwise it returns false/nothing.

    What is Filter_var function in PHP?

    filter_var[] is a PHP function used to filters a variable with the help of a specified filter. In PHP programming language we can use filter_var[] function to validate and sanitize a data such as email id, IP address etc.

    Chủ Đề