Open In App

How to extract Numbers From a String in PHP ?

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.

Example 1:






<?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
    $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

Article Tags :