Home >Backend Development >PHP Tutorial >Tutorial on extracting numbers from string in php
Strings are what we programmers must come into contact with legal persons. Sometimes we need to extract all the numbers from a string at work. In fact, there are quite a lot of research on this method. How to use PHP to extract the numbers in a string? We have made a small summary of the functions of number extraction and would like to share it with you. The three methods are summarized as follows:
The first method uses regular expressions:
function findNum($str=''){ $str=trim($str); if(empty($str)){return '';} $reg='/(\d{3}(\.\d+)?)/is';//匹配数字的正则表达式 preg_match_all($reg,$str,$result); if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){ return $result[1][0]; } return ''; }
The second method Method, use the in_array method:
function findNum($str=''){ $str=trim($str); if(empty($str)){return '';} $temp=array('1','2','3','4','5','6','7','8','9','0'); $result=''; for($i=0;$i<strlen($str);$i++){ if(in_array($str[$i],$temp)){ $result.=$str[$i]; } } return $result; }
The third method, use the is_numeric function:
function findNum($str=''){ $str=trim($str); if(empty($str)){return '';} $result=''; for($i=0;$i<strlen($str);$i++){ if(is_numeric($str[$i])){ $result.=$str[$i]; } } return $result; }
The above three methods are all methods of extracting numbers in strings using PHP. You can Choose the one that suits you best.
Related recommendations:
Solution to the problem of Chinese garbled characters when php intercepts strings
php function strtr to convert specific characters in a string ()
php intercepts the function substr() that returns a string
The above is the detailed content of Tutorial on extracting numbers from string in php. For more information, please follow other related articles on the PHP Chinese website!