PHP: Extracting Numbers from Text (3 Approaches)

Updated: January 9, 2024 By: Guest Contributor Post a comment

Overview

Extracting numbers from a string is a common problem in programming, and PHP offers several ways to accomplish this task. Here, we’ll delve into various methods to retrieve numbers from a block of text using PHP. Each method may be appropriate for different scenarios, depending on the complexity and nature of the text you are working with.

Regular Expression Matching

This solution employs PHP’s preg_match_all function, which searches for all occurrences of a pattern within a string. Regular expressions are powerful and flexible, making them ideal for parsing complex strings.

Steps:

  1. Define the text from which you want to extract numbers.
  2. Create a regular expression that matches the type of numbers you expect (integers, decimals, etc.).
  3. Use preg_match_all to find all matches in the text.
  4. Access the matches from the resulting array.

Example:

<?php
$text = 'The price is 123.45 USD';
$pattern = '/\d+(?:\.\d+)?/';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
?>

Notes: This method is highly reliable for strings containing complex patterns of numbers, although crafting the right regex pattern may be challenging for beginners. Watch out for performance issues with very long strings or highly complex patterns.

String Splitting

This more simplistic approach involves splitting the text into an array using a delimiter with the explode function and then parsing each element for numbers.

Steps:

  1. Choose a non-numeric delimiter to split the text.
  2. Split the text into an array using explode.
  3. Loop through the array to parse individual elements for numbers.
  4. Use is_numeric or other type-checking functions to validate.

Example:

<?php
$text = 'Order number 23453: QTY 10';
$words = explode(' ', $text);
$num_array = array();

foreach ($words as $word) {
    if (is_numeric($word)) {
        $num_array[] = $word;
    }
}

print_r($num_array);
?>

Notes: This is a simple and easy method to implement but could fail if the numbers are not separated by spaces or consistent delimiters. This method might not work for all number formats (e.g., decimals could be split if using period as delimiter).

Filter Functions

PHP’s array_filter function can be used in conjunction with a callback that checks if a value is numeric, providing an elegant way to filter out numbers from an array that has been previously split.

Steps:

  1. Split the text into an array.
  2. Use array_filter with a callback to retain only numeric values.

Example:

<?php
$text = 'Box #42 contains 5 widgets';
$pieces = explode(' ', $text);

$isNumber = function($value) {
    return is_numeric($value);
};

$numbers = array_filter($pieces, $isNumber);
print_r(array_values($numbers));
?>

Notes: This solution is clean and functional without falling back on regular expressions. Best used when numeric values are clearly separated from other text by whitespace or other delimiters.

Conclusion

In conclusion, extracting numbers from text can be approached in multiple ways in PHP. The choice of method depends on the specific requirements of the task at hand, such as the pattern complexity and performance considerations. Using regular expressions with preg_match_all is a versatile option, while explode and parse offer simplicity when dealing with well-formatted strings. Array filter with callback is a functional programming approach that can lead to very readable code. It’s important to consider the nature of your text and potentially combine approaches to achieve the desired results.