HomeLanguagesHow to extract Numbers From a String in PHP ?

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.

  •   /[^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
RELATED ARTICLES

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS