How to extract Numbers From a String in PHP ?
Last Updated :
21 May, 2021
The purpose of this article is to extract numbers from a string using PHP.
Approach:
We can use the preg_replace() function for the extraction of numbers from the string.
- /[^0-9]/ pattern is used for finding number as integer in the string (Refer to Example 1)
- /[^0-9\.]/ pattern is used for finding number as double in the string (Refer to Example 2)
Example 1:
PHP
<?php
$string = '$ 90,000,000.0098';
echo preg_replace("/[^0-9]/", '', $string);
echo "\n<br/>";
$string2 = '$ 90,000,000.0098';
echo preg_replace("/[^0-9\.]/", '', $string2);
?>
|
Output
900000000098
90000000.0098
Example 2: The complete code for extracting number from the string is as follows
PHP
<?php
$string = '$ 90,000,000.0098';
echo preg_replace("/[^0-9]/", '', $string);
echo "\n<br/>";
$string2 = '$ 90,000,000.0098';
echo preg_replace("/[^0-9\.]/", '', $string2);
echo "\n<br/>";
$string3 = 'Jack has 10 red and 14 blue balls';
echo preg_replace("/[^0-9]/", '', $string3);
echo "\n";
?>
|
Output
900000000098
90000000.0098
1014
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...