How to extract numbers from a string in PHP

3 Answers

0 votes
$s = "Today i like the number 31 and the number 13 tomorrow... maybe 100 :-)";

preg_match_all('!\d+!', $s, $numbers);

print_r($numbers);



/*
run:

Array ( [0] => Array ( [0] => 31 [1] => 13 [2] => 100 ) )

*/


answered Nov 5, 2014 by avibootz
edited Apr 13, 2024 by avibootz
0 votes
$s = '12php 36java20';
 
preg_match_all('!\d+!', $s, $num_matches);
 
print_r($num_matches[0]);
 
 
   
   
/*
run:
        
Array ( [0] => 12 [1] => 36 [2] => 20 ) 
       
*/

 



answered Apr 13, 2024 by avibootz
0 votes
$s = '12php 36java20 90 01';
  
preg_match_all('!\d+!', $s, $num_matches);
  
foreach ($num_matches[0] as $val) {
    echo $val . "\n";
}
  
    
    
/*
run:
         
12
36
20
90
01
        
*/

 



answered Apr 13, 2024 by avibootz

Related questions

2 answers 213 views
1 answer 206 views
1 answer 207 views
1 answer 167 views
1 answer 83 views
1 answer 85 views
...