且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过使用php中的regexp在数组中查找数字?

更新时间:2022-10-24 18:30:30

array_filter()是前往此处的方法。

  $ array = array_filter($ array,function($ value){
return preg_match('/ ^ [0-9] + $ /',$ value);
});

您可能还想将preg_match()替换为is_numeric()以提高性能。

  $ array = array_filter($ array,function($ value){
return is_numeric($ value);
});

应该给出相同的结果。


i am using $front->getRequest()->getParams() to get the url params. They look like this

Zend_Debug::dump($front->getRequest()->getParams());

array(4) {
  ["id"] => string(7) "3532231"
  ["module"] => string(7) "test"
  ["controller"] => string(6) "index"
  ["action"] => string(5) "index"
}

i am interested in running this through preg_match_all to get back only the id numbers by using some regexp similar to ([\s0-9])+

for some reason i cant isolate that number.

There is the possibility that there will be more id like values in the array, but the preg_match_all should give them back to me in a new array

any ideas?

thanks

array_filter() is the way to go here.

$array = array_filter($array, function($value) {
    return preg_match('/^[0-9]+$/',$value);
});

You might also want to replace the preg_match() with is_numeric() for performance.

$array = array_filter($array, function($value) {
    return is_numeric($value);
});

That should give the same results.