PHP: How to extract numbers from a string (text)

Posted on October 5, 2008, under PHP 

This is a short function that extracts numbers from a string:

function extract_numbers($string)
{
preg_match_all('/([\d]+)/', $string, $match);

return $match[0];
}

$string = 'Lorem ipsum dolor sit 45 40 amet, consectetuer adipiscing elit. 35 65675 Suspendisse sed nibh non diam consectetuer pharetra. Morbi ultricies 235 536pede et pede. 9432 3536 Nunc eu risus eget quam lacinia feugiat. In sapien sem, fringilla quis, 34 24 8762condimentum id, bibendum ut, nibh. Quisque 2367 784 elementum massa 350 235 vel nulla.';

$numbers_array = extract_numbers($string);

echo '<pre>'; print_r($numbers_array); echo "</pre>";

Output:

Array
(
    [0] => 45
    [1] => 40
    [2] => 35
    [3] => 65675
    [4] => 235
    [5] => 536
    [6] => 9432
    [7] => 3536
    [8] => 34
    [9] => 24
    [10] => 8762
    [11] => 2367
    [12] => 784
    [13] => 350
    [14] => 235
)

Comment via Facebook

comments

9 Replies to "PHP: How to extract numbers from a string (text)"

  1. This code is very used special problems.

  2. sure helps…i am a php newbie
    thanks

  3. love your blog design ;)

  4. Hello

    thanks for nice snippet

  5. Thanks for the snippet, help med in a project i’m working on!

  6. It’s working for me thanks mate.

    PS: So simple and so useful for me, you have no idea…

    Cheers

  7. Thank you very much for this function. I really appreciate it, it help me a lot.

  8. Thanks a lot!
    But how to deal with numbers like 50.000?
    it returns 50 and 000 :-/
    [2] => 5
    [3] => 000

  9. Cirux, use preg_match_all(‘/([d.]+)/’, $string, $match);

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.