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


how to find only numbers in a array by using regexp in php?

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

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应该在新数组中将它们还

给我

有什么想法吗?

谢谢

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

这应该给出相同的结果。

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

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

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

不要为数组中的每个元素迭代preg_match()

is_numeric是非常宽容的,可能因情况而异。

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

方法:(演示)

$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