How To Get Numbers From String In PHP
* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.
In PHP, extracting numbers from a string is a common task, especially when working with data parsing, validation, or processing user inputs.
Whether you need to check if a string contains numbers, extract them into variables, or sum them up, PHP provides multiple ways to achieve this.
In this guide, we will explore different methods to extract numbers from a string, discuss their advantages and disadvantages, and provide best practices for handling numerical data in PHP.
Basic Method: Using preg_match_all()
The most effective way to extract numbers from a string is by using the preg_match_all()
function with a regular expression:
<?php
$string = "Order ID: 12345, Amount: 678.90";
preg_match_all('/\d+\.?\d*/', $string, $matches);
print_r($matches[0]);
?>
Pros:
- Works well with both integers and decimal numbers.
- Returns all numbers in an array.
Cons:
- Requires understanding of regular expressions.
- Can be overkill for simple numeric extraction.
Extracting Numbers Using filter_var()
Another way to extract numbers from a string is by using filter_var()
with the FILTER_SANITIZE_NUMBER_INT
filter:
<?php
$string = "Order ID: 12345";
$number = filter_var($string, FILTER_SANITIZE_NUMBER_INT);
echo $number; // Output: 12345
?>
Pros:
- Simple and easy to use.
- Works well for extracting whole numbers.
Cons:
- Removes decimal points, making it unsuitable for floating-point numbers.
- Does not return an array of numbers.
Extracting Numbers with str_replace()
If you only need to remove non-numeric characters, str_replace()
can be a simple solution:
<?php
$string = "Amount: $678.90";
$number = str_replace(['$', ','], '', $string);
echo $number; // Output: 678.90
?>
Pros:
- Simple for removing known unwanted characters.
- Useful for cleaning up formatted numbers.
Cons:
- Does not extract multiple numbers from a string.
- Requires manual specification of unwanted characters.
Converting Extracted Numbers to an Array
If you have multiple numbers in a string and want to store them in an array, you can use preg_match_all()
as shown earlier:
<?php
$string = "Product IDs: 1001, 2025, 3078";
preg_match_all('/\d+/', $string, $matches);
$numbers = $matches[0];
print_r($numbers);
?>
This stores all extracted numbers in an array, making it easier to work with multiple values.
Summing Extracted Numbers
If you need to extract numbers from a string and sum them, you can combine preg_match_all()
with array_sum()
:
<?php
$string = "Order 1: 150.5, Order 2: 349.75";
preg_match_all('/\d+\.?\d*/', $string, $matches);
$sum = array_sum($matches[0]);
echo "Total: " . $sum; // Output: 500.25
?>
Pros:
- Efficient way to sum numbers from a string.
- Works with both integers and floats.
Cons:
- Needs regex parsing before summing.
Summary of Methods
Method | Best For | Pros | Cons |
---|---|---|---|
preg_match_all() | Extracting multiple numbers | Works with all number types | Requires regex knowledge |
filter_var() | Extracting single integer | Simple to use | Removes decimal points |
str_replace() | Removing unwanted characters | Quick and easy | Does not handle multiple numbers |
array_sum() | Summing extracted numbers | Works with extracted arrays | Needs regex preprocessing |
Conclusion
Extracting numbers from a string in PHP can be done in multiple ways, each with its strengths and limitations. Whether you need to extract, clean, or sum numbers, using the right approach ensures efficient data processing.