#How to implement PHP to only retain numbers?
1. Use regular expressions to match all numbers and extract them, or replace characters that are not numbers;
<?php $str='acc123nmnm4545'; if(preg_match('/\d+/',$str,$arr)){ echo $arr[0]; } ?>
2. Split the string into an array and traverse it The array determines whether each character is a number, and if so, it can be extracted.
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; }
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; }
Recommended tutorial: "PHP"
The above is the detailed content of How to implement PHP to only retain numbers?. For more information, please follow other related articles on the PHP Chinese website!