php把一个格式化的文件转换为一个二维数组

来源:互联网 发布:网络推广部职责学生会 编辑:程序博客网 时间:2024/05/16 05:42
      这段时间 有机会使用php做一些字符处理方面的工作,顺便学习了一下php强大的字符处理功能。下面就这一方面做个总结。
  1. <?php
  2. /× 如果让一个php程序,从输入获得运行时参数?
  3.  × php使用的方法和c语言类似,也是argc是参数个数,argv是参数表
  4.  ×  具体使用如下
  5. ×/
  6. $argc = $_SERVER['argc'];
  7. if( $argc != 3 )
  8. {
  9.  printf(" input <filename> <varibaleNumPerLine>\n " );
  10.  return;
  11. }

  12. $filename = $_SERVER["argv"][1];
  13. $counts = $_SERVER["argv"][2];

  14. $store = array();
  15. $index = 0;
  16. /× php如何读文件?
  17. × 下面这段代码是手册上给出的标准格式,建议大家参考使用
  18. ×/
  19. $readh = fopen($filename, "r");
  20. if( $readh )
  21. {
  22.  while( ($buffer = fgets($readh)) !== false )
  23.  {
  24.   $buffer = trim($buffer);
  25. /* 这行是正则表达式,去掉多余空格,非常有用*/
  26.   $buffer = preg_replace('/\s(?=\s)/', '', $buffer);
  27.   printf("%s\n", $buffer);
  28.   $tmparray = explode(' ', $buffer);
  29.   if( count( $tmparray ) != $counts )
  30.   {
  31.    printf(" the file format does not correspond the expect \n");
  32.    printf(" wrong line is %s\n ", $buffer );
  33.    continue;
  34.   }

  35. /* 构建二维数组 */
  36.   $store[$index] = array();
  37.   for( $i = 0 ; $i < $counts; $i++ )
  38.   {
  39.    $store[$index][$i] = $tmparray[$i];
  40.   }
  41.   $index++; 


  42.  }
  43.  if( !feof($readh) )
  44.  {
  45.   printf("Error: unexpected fgets() faile\n");
  46.  }
  47. }
  48. fclose($readh);

  49. foreach( $store as $fkey => $fvalue )
  50. {
  51.  printf(" the %dth line \n", $fkey );
  52.  foreach( $fvalue as $skey => $svalue )
  53.  {
  54.   printf("value is %s\n", $svalue );
  55.  }
  56. }
  57. ?>

这个简单的小程序,可以把一个文件里用空格隔开的一些字符和数字,最后完全存入到一个二维数组中,并最后打印展示。
希望对大家有用!




原创粉丝点击