How to implement php to only take numbers: 1. Use the "preg_match" function to extract numbers from the string; 2. Use PHP's built-in "in_array" method to extract all the numbers that appear in the string. And spliced together; 3. Use the "is_numeric" method.
php Extract numbers from the string
1. Regular extraction [Only extract the first occurrence Numbers]
<?php $str ='我是123456一段测试的字789符串00'; preg_match('/\d+/',$str,$number); print_r($number); ?>
2. Regular extraction [All numbers appearing in the string are extracted in array form]
<?php $str ='我是123456一段测试的字789符串00'; preg_match_all('/\d+/',$str,$arr); print_r($arr); ?>
3. Use in_array Method [Extract all the numbers that appear in the string and splice them together in string form] Pay attention to the encoding issue
$str='我是123456一段测试的字789符串00'; $str=trim($str); if (!empty($str)) { $key = ['0','1','2','3','4','5','6','7','8','9']; $number = ''; for ($i = 0;$i < strlen($str);$i++) { if (in_array($str[$i],$key)){ $number .= $str[$i]; } } } print_r($number);
4. Use the is_numeric method like the in_array method
The above is the detailed content of How to implement the function of taking only numbers in php. For more information, please follow other related articles on the PHP Chinese website!