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
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS)
DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers
NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers
HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface)
In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network
A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read