【问题标题】:how to filter array value that contains numbers only如何过滤仅包含数字的数组值
【发布时间】:2017-06-14 06:10:09
【问题描述】:

我有一个文件作为数组 '行号' => '它的内容'; 现在我需要一种方法来删除只包含数字的行(没有字母或特殊字符) 我是按行长做的,但这种方法不合适,因为它可能会删除一些内容

/*count file lines*/
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
}
fclose($handle);

for($i=0; $i<=($linecount*2)-4;$i++) {
    $length = strlen((string)$text[0][$i]);
    if ($length >5) 
    {
        echo ($text[0][$i] .'</br>');
    }

}

我认为is_numric 不起作用,因为数字前有一个空格

【问题讨论】:

  • 如何使用is_numeric($value)
  • 已经试过了,但没用,我猜是因为数字前有空格
  • 尝试为此使用正则表达式
  • 或许提供一些示例数据可能有助于其他人更好地理解问题?
  • 如果有空格,则使用is_numeric(trim($value));...

标签: php


【解决方案1】:

我修改了第二行。不明白为什么$length>5,应该是$length>0

strlen(trim((string)$text[0][$i]));

for($i=0; $i<=($linecount*2)-4;$i++) {
$length = strlen(trim((string)$text[0][$i]));
if ($length >0) 
   {
       echo ($text[0][$i] .'</br>');
   }

}

【讨论】:

    【解决方案2】:

    请试试这个

    $keys=array_filter(array_keys($array1), "is_numeric");
    $out =array_diff_key($array1,array_flip($keys));
    print_r($out);
    

    【讨论】:

      【解决方案3】:

      试试这个:

      $pattern = '/^[0-9 ]+$/';
      
      if ( !preg_match ($pattern, $text) )
      {
          echo 'allowed';
      }
      

      来自here

      【讨论】:

        【解决方案4】:

        由于没有给出示例数据,因此我根据给定描述的假设数据输入给出了这个答案 - 它很可能与实际数据没有相似之处。

        我使用的输入文件有以下几行数据——字符和数字的混合

        abc23
        123
        89
        gh46m
        12 34 56
        
        
        $file='c:/temp/src.txt';
        
        $lines=array_filter( file( $file ), function( $item ){
            $pttn='@^[0-9\s]{1,}$@';
            preg_match( $pttn, $item ,$matches );
            return count( $matches ) > 0 ? true : false;
        });
        
        echo '<pre>',print_r($lines,true),'</pre>';
        

        这会输出以下内容:

        Array
        (
            [1] => 123
        
            [2] => 89
        
            [4] => 12 34 56
        )
        

        如果 space 算作特殊字符,则只需通过删除 \s 来修改正则表达式模式,这应该只匹配数字

        【讨论】:

          猜你喜欢
          • 2021-12-12
          • 1970-01-01
          • 2018-02-28
          • 2021-03-17
          • 1970-01-01
          • 2019-08-15
          • 2022-11-28
          • 2012-02-15
          • 1970-01-01
          相关资源
          最近更新 更多