Php method for extracting numbers from a string
Sometimes we need to extract all the numbers in a string of strings in PHP development, and there are a lot of ways to find out, and it's worth documenting.
A small summary of how to use PHP to extract the numbers from a string is summarized in three ways as follows:
1. Use Regular Expressions:
function FindNum ($str = ") {
$str =trim ($STR);
if (empty ($STR)) {return ';}
$reg = '/(\d{3} (\.\d+)?) /is ';//Regular expression that matches 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 ';
}
2. Using 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
<>
if (In_array ($str [$i], $temp)) {
$result. = $str [$i];
}
}
return $result;
}
3. Use the Is_numeric function:
function FindNum ($str = ") {
$str =trim ($STR);
if (empty ($STR)) {return ';}
$result = ";
for ($i =0; $i
<>
if (Is_numeric ($str [$i])) {
$result. = $str [$i];
}
}
return $result;
}