Friday, October 17, 2025
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
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS