Open In App

How to extract numbers from string in PHP ?

Last Updated : 16 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Extracting numbers from a string in PHP involves isolating numeric values within mixed text. This is essential for data validation, processing, and analysis, allowing developers to retrieve and utilize numerical information from user input, database entries, or external sources, ensuring accurate and relevant data handling.

Methods:

Using preg_match_all() Function

The preg_match_all() function in PHP extracts numbers from a string using regular expressions. By matching patterns of digits, like /\d+/, it identifies and retrieves all numeric values, returning them as an array, making it a precise and efficient approach.

Syntax:

preg_match_all('/\d+/', $string, $matches);

Example: In this example we extracts all numbers from a string using preg_match_all with a regular expression. It captures the numbers into an array and prints them.

<?php
// Sample string with numbers
$string = "The order numbers are 123, 456, and 789.";

// Using preg_match_all to extract numbers
preg_match_all('/\d+/', $string, $matches);

// Extracted numbers
$numbers = $matches[0];

// Print the extracted numbers
print_r($numbers);
?>

Output
Array
(
    [0] => 123
    [1] => 456
    [2] => 789
)

Using  preg_replace() Function

The preg_replace() function in PHP removes non-numeric characters from a string, effectively extracting numbers. By using a pattern like /\D+/, which matches any non-digit characters, and replacing them with an empty string, it isolates the numeric values within the string.

Syntax:

preg_replace( $pattern, $replacement, $subject, $limit, $count )

Return Value: This function returns an array if the subject parameter is an array, or a string otherwise.

Example: In this example we use preg_replace to remove non-numeric characters from a string, leaving only the numbers. It then prints the extracted numbers from the string.

<?php

    // PHP program to illustrate
   // preg_replace function

   // Declare a variable and initialize it
   $geeks = 'Welcome 2 Geeks 4 Geeks.';

  // Filter the Numbers from String
  $int_var = preg_replace('/[^0-9]/', '', $geeks);  

   // print output of function
   echo("The numbers are: $int_var \n"); 


?>

Output
The numbers are: 24 

Using preg_split() and array_filter() Functions

Using preg_split() and array_filter() functions in PHP extracts numbers by splitting the string at non-numeric characters with a pattern like /\D+/. Then, array_filter() removes empty values, leaving only numeric elements, effectively isolating the numbers from the string.

Example: In this example we use preg_split to separate digits from a string, filters out empty parts, and combines the numbers into a single string.

<?php
    function extractNumbersUsingSplit($string){
        $parts = preg_split('/\D+/', $string);
        $numbersArray = array_filter($parts, fn($part) => $part !== '');
        $numbers = implode('', $numbersArray);
        return $numbers;

    }
    $string = "Welcome 1234 to PHP 5678 World.";
    echo extractNumbersUsingSplit($string);

?>

Output
12345678

This approach is particularly useful when you need to extract numbers that are separated by non-digit characters, while automatically handling cases where multiple non-digit characters are present consecutively.



Next Article

Similar Reads

three90RightbarBannerImg