How to extract numbers from string in PHP ?
Last Updated :
16 Sep, 2024
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
<?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);
?>
OutputArray
(
[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
// 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");
?>
OutputThe 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
<?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);
?>
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.
Similar Reads
How to Extract Substring from a String in PHP?
Given a String, the task is to extract a substring from a string in PHP. Extracting substrings from a string is a common task in PHP, whether you need to extract a portion of text based on a specific position or find a substring based on a pattern. In this article, we will explore various approaches
3 min read
How to find number of characters in a string in PHP ?
We have given a string and the task is to count number of characters in a string str in PHP. In order to do this task, we have the following methods in PHP:Table of ContentMethod 1: Using strlen() MethodMethod 2: Using mb_strlen() MethodMethod 3: Using iconv_strlen() MethodMethod 4: Using grapheme_s
3 min read
How to get parameters from a URL string in PHP?
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions.Note: The page URL and the parameters are separated by the ? character.parse_url() FunctionThe parse_url() function is used to return the components of a URL by parsing it. It parses a URL and return
2 min read
How to Copy String in PHP ?
Copying a string is a basic operation that all the programming languages offer. In this article, we will explore different approaches to copying a string in PHP, including using the assignment operator, the strval() function, the substr() function and by implementing the strcpy() function.Table of C
3 min read
How to remove extension from string in PHP?
There are three ways of removing an extension from string. They are as follows Using an inbuilt function pathinfo Using an inbuilt function basename Using an string functions substr and strrpos Using pathinfo() Function: The pathinfo() function returns an array containing the directory name, basenam
2 min read
How to get String Length in PHP ?
In this article, we learn how to find the length of the string in PHP. Approach: This task can be done by using the built-in function strlen() in PHP. This method is used to return the length of the string. It returns a numeric value that represents the length of the given string. Syntax: strlen($st
1 min read
How to Sort Numeric Array in PHP?
Given a numeric array, the task is to sort the numeric array using PHP. There are various built-in functions to sort arrays in different ways. Below are the approaches to sort numeric arrays in PHP:Table of ContentUsing sort() FunctionUsing rsort() FunctionUsing asort() FunctionUsing arsort() Functi
3 min read
How to count the number of words in a string in PHP ?
Given a string containing some words and the task is to count number of words in a string str in PHP. In order to do this task, we have the following approaches:Table of ContentUsing str_word_count() MethodUsing trim(), preg_replace(), count() and explode() method. Using trim(), substr_count(), and
4 min read
How to add a Character to String in PHP ?
Given two strings, the task is to add a Character to a String in PHP. The character can be added to a string in many ways in this article we will be using eight methods including the Concatenate Method, the String Interpolation Method, the str_pad() Method, Concatenation Assignment (.=) Operator, St
5 min read
How to Iterate Over Characters of a String in PHP ?
This article will show you how to iterate over characters of string in PHP. It means how to loop through an array of characters in a string. There are two methods to iterate over the character of a string, these are:Table of ContentUsing str_split() function and foreach LoopUsing for LoopUsing mb_su
3 min read