Home >Backend Development >PHP Tutorial >基础题,通过递归正则匹配数字元素

基础题,通过递归正则匹配数字元素

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-23 14:05:39841browse

digui函数程序功能为通过递归正则匹配数字

如果是数字就保存到新数组中保存,最后返回所有包含数字的元素的数组


$array=array(
"22",
"1234",
array("a",
   array("aab","00000","aaa","222000","3333000"),
   "aa","999","aaaa"),
"d",
"567",
"33",
"dsf");
$fl_array=array();
function digui($arr)

    global $fl_array;
foreach($arr as $key=>$value)
{
    if (is_array($value))
    {
   digui($value);
    }
}

$fl_array = preg_grep("/\d+/", $arr);   

return $fl_array;

}

print_r(digui($array));
?>


回复讨论(解决方案)

$array=array(  "22",  "1234",  array(    "a",    array("aab","00000","aaa","222000","3333000"),    "aa","999","aaaa"),  "d",  "567",  "33",  "dsf");function digui($arr) {   $fl_array = array();  foreach($arr as $key=>$value) {    if(is_array($value)) {      $fl_array = array_merge($fl_array, digui($value));    }  }  $fl_array = array_merge($fl_array, @preg_grep("/\d+/", $arr));     return $fl_array;}print_r(digui($array));
Array
(
    [0] => 00000
    [1] => 222000
    [2] => 3333000
    [3] => 999
    [4] => 22
    [5] => 1234
    [6] => 567
    [7] => 33
)

$result=array();global $result;function getNum($arr){ 	global $result;	foreach ($arr as $value) {		if(is_array($value)){			getNum($value);		}		if(is_numeric($value)){			array_push($result, $value);		}	}	return $result;}print_r(getNum($array));
这样好像也可以

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn