muugua 发表于 2017-4-11 09:48:00

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

这段时间 有机会使用php做一些字符处理方面的工作,顺便学习了一下php强大的字符处理功能。下面就这一方面做个总结。

[*]<?php
[*]/× 如果让一个php程序,从输入获得运行时参数?
[*]× php使用的方法和c语言类似,也是argc是参数个数,argv是参数表
[*]× 具体使用如下
[*]×/
[*]$argc = $_SERVER['argc'];
[*]if( $argc != 3 )
[*]{
[*]printf(" input <filename> <varibaleNumPerLine>\n " );
[*]return;
[*]}
[*]

[*]$filename = $_SERVER["argv"];
[*]$counts = $_SERVER["argv"];
[*]
[*]$store = array();
[*]$index = 0;
[*]/× php如何读文件?
[*]× 下面这段代码是手册上给出的标准格式,建议大家参考使用
[*]×/
[*]$readh = fopen($filename, "r");
[*]if( $readh )
[*]{
[*]while( ($buffer = fgets($readh)) !== false )
[*]{
[*] $buffer = trim($buffer);
[*]/* 这行是正则表达式,去掉多余空格,非常有用*/
[*] $buffer = preg_replace('/\s(?=\s)/', '', $buffer);
[*] printf("%s\n", $buffer);
[*] $tmparray = explode(' ', $buffer);
[*] if( count( $tmparray ) != $counts )
[*] {
[*] printf(" the file format does not correspond the expect \n");
[*] printf(" wrong line is %s\n ", $buffer );
[*] continue;
[*] }
[*]

[*]/* 构建二维数组 */
[*] $store[$index] = array();
[*] for( $i = 0 ; $i < $counts; $i++ )
[*] {
[*] $store[$index][$i] = $tmparray[$i];
[*] }
[*] $index++;
[*]

[*]

[*]}
[*]if( !feof($readh) )
[*]{
[*] printf("Error: unexpected fgets() faile\n");
[*]}
[*]}
[*]fclose($readh);
[*]

[*]foreach( $store as $fkey => $fvalue )
[*]{
[*]printf(" the %dth line \n", $fkey );
[*]foreach( $fvalue as $skey => $svalue )
[*]{
[*] printf("value is %s\n", $svalue );
[*]}
[*]}
[*]?>
[*]


这个简单的小程序,可以把一个文件里用空格隔开的一些字符和数字,最后完全存入到一个二维数组中,并最后打印展示。
希望对大家有用!
----------------------------------------分割线-----------------------------------------
接下来准备去做LCD、IGBT、HMI方面的电商
页: [1]
查看完整版本: php把一个格式化的文件转换为一个二维数组