- Php numbers only from string
- Extract Numbers From a String in PHP
- Use preg_match_all() Function to Extract Numbers From a String in PHP
- Use filter_var() Function to Extract Numbers From a String in PHP
- Use preg_replace() Function to Extract Numbers From a String in PHP
- Related Article — PHP String
- Extract Numbers From String in PHP
- Use preg_match_all() method
- Use preg_replace() method
- PHP: Get numbers from a string.
- The preg_match_all function.
- Getting integers / whole numbers from a string.
- Extracting decimal numbers.
Php numbers only from string
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
Extract Numbers From a String in PHP
- Use preg_match_all() Function to Extract Numbers From a String in PHP
- Use filter_var() Function to Extract Numbers From a String in PHP
- Use preg_replace() Function to Extract Numbers From a String in PHP
In this article, we will introduce methods to extract numbers from a string in PHP.
- Using preg_match_all() function
- Using filter_variable() function
- Using preg_replace() function
Use preg_match_all() Function to Extract Numbers From a String in PHP
We can use the built-in function preg_match_all() to extract numbers from a string . This function globally searches a specified pattern from a string . The correct syntax to use this function is as follows:
preg_match_all($pattern, $inputString, $matches, $flag, $offset);
This function returns a Boolean variable. It returns true if the given pattern exists.
The program below shows how we can use the preg_match_all() function to extract numbers from a given string .
php $string = 'Sarah has 4 dolls and 6 bunnies.'; preg_match_all('!\d+!', $string, $matches); print_r($matches); ?>
We have used !\d+! pattern to extract numbers from the string .
Array ( [0] => Array ( [0] => 4 [1] => 6 ) )
Use filter_var() Function to Extract Numbers From a String in PHP
We can also use the filter_var() function to extract numbers from a string . The correct syntax to use this function is as follows:
filter_var($variableName, $filterName, $options)
The function filter_var() accepts three parameters. The detail of its parameters is as follows
We have used FILTER_SANITIZE_NUMBER_INT filter. The program that extracts numbers from the string is as follows:
php $string = 'Sarah has 4 dolls and 6 bunnies.'; $int = (int) filter_var($string, FILTER_SANITIZE_NUMBER_INT); echo("The extracted numbers are: $int \n"); ?>
The extracted numbers are: 46
Use preg_replace() Function to Extract Numbers From a String in PHP
In PHP, we can also use the preg_replace() function to extract numbers from a string . The correct syntax to use this function is as follows:
preg_replace($regexPattern, $replacementVar, $original, $limit, $count)
We will use the pattern /[^0-9]/ for finding numbers in the string . The program that extracts numbers from the string is as follows:
php $string = 'Sarah has 4 dolls and 6 bunnies.'; $outputString = preg_replace('/[^0-9]/', '', $string); echo("The extracted numbers are: $outputString \n"); ?>
The extracted numbers are: 46
Related Article — PHP String
Copyright © 2023. All right reserved
Extract Numbers From String in PHP
This approach isn’t efficient for certain use case, and simply returns the numbers present within the string together. For a more efficient, we can rely on regular expression.
Use preg_match_all() method
Use preg_match_all() method with /2+/ to extract numbers from String in PHP.
Here, output is array of matches, which can then be used to extract the numbers from the string.
We used the preg_match_all() function to search for the regular expression and extracted the numbers from the string.
We used regular expression in the form of a pattern /5+/ that matched the numbers in the string.
preg_match_all performs global regular expression match. It takes three arguments:
$pattern : The pattern to be searched
$subject : Input String
$matches :Array of all matches in the String.
Use preg_replace() method
We can achieve the same output as the filter_var method using regular expression where we replace all the characters that are not numbers with empty whitespace. The regular expression match value would be /[^0-9]/ .
Let’s illustrate this approach on the same string as in the previous section.
PHP: Get numbers from a string.
This is a short PHP tutorial on how to get numbers from a string. To do this, we will extract the numbers using the function preg_match_all.
The preg_match_all function.
The preg_match_all function allows us to match certain characters using regular expressions. In our case, we want to match numerical values.
Getting integers / whole numbers from a string.
If you’re looking to extract whole numbers from a string, then you can use the following piece of code:
//A string containing two integer values. $str = 'There are 330 days until Christmas. It is currently 12PM.'; //Extract the numbers using the preg_match_all function. preg_match_all('!\d+!', $str, $matches); //Any matches will be in our $matches array var_dump($matches);
If you run the code above, you will get the following result:
Extracting numbers from a string in PHP.
As you can see, we were able to extract the integers from our string by using PHP’s preg_match_all function.
But what if we also want to be able to extract decimal numbers?
Extracting decimal numbers.
To extract decimal and float numbers from a string, we will have to use a different regular expression. Otherwise, our code in the previous example will split the numbers up.
//A string that contains both an integer and a decimal number. $string = 'A 2 euro coin weighs 8.5 grams.'; //Extract the numbers using the preg_match_all function. preg_match_all('!\d+\.*\d*!', $string, $matches); //var_dump the result var_dump($matches);
In the example above, we were able to extract both the whole number and the decimal number. If you var_dump the array, you will see the following result:
A var_dump of our $matches array.
As you can see, we managed to extract both the 2 and the 8.5 from our text.
Hopefully, you found the code above useful!