PHP: How to extract numbers from a string (text)
Posted on October 5, 2008, Filled under PHP,
Bookmark it
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
)
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- October 5, 2008
- article by Gabriel C.
- 6 comments
Related Posts
PHP: Extract Alphabetical Sequences from a Stringat October 5, 2008
PHP: Extract Alphanumeric Sequences from a Stringat October 5, 2008
PHP: Match Non-Alphanumeric Characters from a Stringat October 5, 2008
Shorten a string (text)at September 3, 2008 with 2 comments
How to emphasize specific words from a string (text)at September 6, 2008

6 Replies to "PHP: How to extract numbers from a string (text)"
January 11, 2010 at 3:41 AM
This code is very used special problems.
March 15, 2010 at 7:37 AM
sure helps…i am a php newbie
thanks
April 5, 2010 at 12:11 PM
love your blog design
May 26, 2010 at 12:48 PM
Hello
thanks for nice snippet
May 27, 2010 at 4:48 AM
Thanks for the snippet, help med in a project i’m working on!
June 30, 2010 at 6:44 AM
It’s working for me thanks mate.
PS: So simple and so useful for me, you have no idea…
Cheers