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

吃可爱长大的小学妹 提交于 2019-12-25 17:05:40

问题


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


回答1:


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.




回答2:


Why can't you capture the array and just access the element you want?

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



回答3:


Yes, you can use regex, but a non-regex filter will be more efficient.

DON'T iterate preg_match() for each and every element in the array!

is_numeric is VERY forgiving and may be untrustworthy from case to case.

If you know you want to access the id elements value, just access it directly.

Methods: (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

Output:

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

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

3532231


来源:https://stackoverflow.com/questions/10857589/how-to-find-only-numbers-in-a-array-by-using-regexp-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!