【问题标题】:how to find only numbers in a array by using regexp in php?如何在 php 中使用正则表达式仅查找数组中的数字?
【发布时间】:2012-06-01 21:29:13
【问题描述】:

我正在使用$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 应该在新数组中将它们返回给我

有什么想法吗?

谢谢

【问题讨论】:

    标签: php arrays numbers preg-match-all


    【解决方案1】:

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

    这应该给出相同的结果。

    【讨论】:

    • 闭包在 is_numeric 示例中没有意义:只需使用 array_filter($array, "is_numeric")
    【解决方案2】:

    为什么你不能捕获数组并只访问你想要的元素?

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

    【讨论】:

      【解决方案3】:

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

      不要为数组中的每个元素迭代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
      

      【讨论】:

        猜你喜欢
        • 2020-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多