Thursday, September 4, 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
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS