VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-extract-numbers-from-a-string-in-php/

⇱ How to extract Numbers From a String in PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to extract Numbers From a String in PHP ?

Last Updated : 23 Jul, 2025

Extracting numbers from a string involves identifying and isolating numerical values embedded within a text. This process can be done using programming techniques, such as regular expressions, to filter out and retrieve only the digits from the string, ignoring all other characters.

Here we have some common approaches:

Using preg_replace() function

We can use thepreg_replace() function for the extraction of numbers from the string.

  • /[^0-9]/ pattern is used for finding number as integer in the string (Refer to Example 1)
  • /[^0-9\.]/ pattern is used for finding number as double in the string (Refer to Example 2)

Example 1:


Output
900000000098
90000000.0098

Example 2: The complete code for extracting number from the string is as follows


Output
900000000098
90000000.0098
1014

Using str_split() and ctype_digit()

Using str_split() and ctype_digit() in PHP, you can extract numbers from a string by splitting it into characters, filtering out the digits, and then joining them back together.

Example:


Output
10050

Using filter_var() and Regular Expressions

The filter_var() function with the FILTER_SANITIZE_NUMBER_INT or FILTER_SANITIZE_NUMBER_FLOAT filters can be used to extract numbers from a string. This approach is useful when you need to sanitize a string and extract an integer or float.

Example : Extracting Integer and Float Numbers Using filter_var()

Here is the complete code for extracting an integer and a float number from a string using filter_var():


Output
900000000098
<br/>90000000.0098
<br/>1014
<br/>

Using preg_match_all()

The preg_match_all() function is used to perform a global regular expression match, which allows us to find all instances of numbers within a string. This method is flexible and can be tailored to extract integers, floats, or any other specific numerical patterns.

Example


Output
Array
(
 [0] => 123
 [1] => 45.67
 [2] => 890.01
)
Comment