如何在PHP中使用正则表达式只查找数组中的数字?

时间:2012-06-01 21:29:14

标签: php arrays numbers preg-match-all

我正在使用$front->getRequest()->getParams()获取网址参数。他们看起来像这样

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

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

我有兴趣通过preg_match_all运行此功能,通过使用与([\s0-9])+

类似的正则表达式来仅返回ID号码 由于某种原因,我无法隔离这个号码。

数组中可能会有更多id个值,但preg_match_all应该以新数组的形式将它们发回给我

任何想法?

感谢

3 个答案:

答案 0 :(得分:3)

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);
});

这应该给出相同的结果。

答案 1 :(得分:2)

为什么不能捕获数组并只访问所需的元素?

$params = $front->getRequest()->getParams();
echo $params['id'];

答案 2 :(得分:0)

是的,你可以使用正则表达式,但非正则表达式过滤器会更有效。

DON' T 为数组中的每个元素迭代preg_match()

is_numeric 非常宽恕,并且可能因情况而不值得信任。

如果您知道要访问id元素值,只需直接访问它。

方法:(Demo

$array=["id"=>"3532231","module"=>"test","controller"=>"index","action"=>"index"];

var_export(preg_grep('/^\d+$/',$array));  // use regex to check if value is fully comprised of digits
// but regex should be avoided when a non-regex method is concise and accurate
echo "\n\n";

var_export(array_filter($array,'ctype_digit'));  // ctype_digit strictly checks the string for digits-only
//  calling is_numeric() may or may not be too forgiving for your case or future readers' cases

echo "\n\n";

echo $array['id']; // this is the most logical thing to do

输出:

array (
  'id' => '3532231',
)

array (
  'id' => '3532231',
)

3532231