我正在创建一个函数,该函数读取制表符分隔的文本文件,然后将值存储在二维数组中 . 文本文件有一行数据,然后只有一行标签(因为它是从excel导出的),我选择使用逗号选项卡,因为某些值中有逗号 .
我打开文件进行阅读,然后使用
$ lines = file($ filename);
将文件的每一行作为元素放在数组中 .
然后我使用这个foreach循环,如果它是所有选项卡的一行,我想取消它,如果它有数据则爆炸它(创建二维数组) .
这是我目前的代码:
//loop through array to either explode into two dimentional array or to unset lines with only tabs(no letters)
foreach($lines as $index => $line)
{
//work around so that it removes any lines with 2 tabs at the begining of the line, we know this because MRN and Patient Name is always included
if (preg_match("/^\t{2}/", $line))
{
unset($lines[$index]);
echo " unset";
}
else
{
$lines[$index] = explode("\t",$line);
echo " explode";
}
}
//use array_values() so that indexes are in standard form in array
$lines = array_values($lines);
echo "
START";
print_r($lines);
echo "END
";这是输入:
Pam Administrator 2 gold
Charlotte Office Organizer 3 purple
这是输出:
unset explode unset explode explode
STARTArray
(
[0] => Array
(
[0] => Pam
[1] => Administrator
[2] => 2
[3] => gold
)
[1] => Array
(
[0] => Charlotte
[1] => Office Organizer
[2] => 3
[3] => purple
)
[2] => Array
(
[0] =>
)
)
END
我的问题是,如果我这样做,preg_match会起作用:
(preg_match("/^\t{2}/", $line))
但如果我这样做,则不起作用:
$tabcount=2;
(preg_match("/^\t{$tabcount}/", $line))
它只是查看它并返回false并且不会取消该行 .
为什么这样做?
先感谢您 .