The recent work in the code to write in a string of all the numbers to be extracted out of such a small function, the study of the discovery method is quite many, it is worth recording, so how to use PHP to extract the number of strings in the function of a small summary, summed up three ways are as follows:
The first method uses a regular expression:
functionFindNum ($str= ' '){ $str=Trim($str); if(Empty($str)){return‘‘;} $reg= '/(\d{3} (\.\d+)?) /is ';//regular expressions that match numbers 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 uses the In_array method:
functionFindNum ($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 uses the Is_numeric function:
functionFindNum ($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;}
PHP extracts numbers in a string