What this article brings to you is about how PHP extracts the numbers in a string. PHP extract the number of strings in the method summary (with code), there is a certain reference value, the need for friends can refer to, I hope to help you.
PHP extracts the first set of numbers in a string
<?php $str = ' acc123nmnm4545 '; if (Preg_match ('/\d+/', $str, $arr)) { echo $arr [0]; }? >
Other ways in which PHP extracts numbers from a string
The first method uses a regular expression:
function FindNum ($str = ") {$str =trim ($STR), if (Empty ($STR)) {return ';} $reg = '/(\d{3} (\.\d+)?) /is ';//match number of regular expression 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:
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 uses 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;}
For example:
Intercept the number in the string 2 $str = ' Q 2 '; $result = "; for ($i =0; $i <strlen ($STR), $i + +) { if (is_numeric ($str [$i])) { $result. = $str [$i]; } } Print_r ($result);d ie; Output Results 2