从空格分隔的文本文件创建PHP数组


Creating a PHP array from space delimited text file

我有一个文本文件,其中列出了我想转换为数组的目录。我认为空格分隔是可行的,但每个项目的空格数量不同,目录名中的空格也会有问题。我想把文本解析成一个PHP数组。

文本文件有一个非常严格的结构,看起来像这样:

04/17/2013  09:49 PM    <DIR>          This is directory 1 (1994)
03/11/2013  06:48 PM    <DIR>          Director 2 (1951)
04/15/2013  08:34 PM    <DIR>          This is going to be number 3 (2000)
08/17/2012  09:50 PM    <DIR>          Four (1998)
10/17/2011  05:12 PM    <DIR>          And lastly 5 (1986)

我只需要在括号中保留文件夹日期(而不是时间)、目录的完整名称(作为一个条目)和年份。提前感谢!

当然,使用preg_split:

<?php
$str = "04/17/2013  09:49 PM    <DIR>          This is directory 1 (1994)
03/11/2013  06:48 PM    <DIR>          Director 2 (1951)
04/15/2013  08:34 PM    <DIR>          This is going to be number 3 (2000)
08/17/2012  09:50 PM    <DIR>          Four (1998)
10/17/2011  05:12 PM    <DIR>          And lastly 5 (1986)";
function sp($x) {
    return preg_split("/'s's+|'s*'(('d{4}).*')/", $x,0,PREG_SPLIT_DELIM_CAPTURE);
}
$array = preg_split("/'n/", $str);
$processed = array_map('sp', $array);
print_r($processed);

这将创建一个数组。每一行都将成为一个数组,包含每个项目的一个数组。例如,$processed[0][3]将包含This is directory 1

请记住,此代码假设作为除法工作的空间必须为2或更多;只有1个空间被认为是同一字段的一部分。(你可能需要根据自己的需要手动破解)

编辑:我添加了部分以将年份作为数组的一个单独元素。现在$processed[0][4]有了1994。(你不需要(),对吧?)

请在此处查看它与此更改的配合:http://codepad.org/in973ijV

为什么不忘记这个txt并使用scandir?

http://php.net/manual/en/function.scandir.php

$mydir = "/home/folder/";
$scan = scandir($mydir);
$i = 2 /* bypass dot and 2dots dirs */;
while($i < count($scan)){
    echo $scan[$i];
    echo "<hr>";
    $i++;
} 

最简单的(读取)模式是:

$pattern = '~^(?<date>'S+).*<DIR>'s+(?<name>.*) '((?<year>'d{4})')$~m';
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    printf("<br>date: %s, name: %s, year: %s",
           $match['date'], $match['name'], $match['year']);
}

但你可以更明确地优化一点:

$pattern = '~^(?<date>'S++)'                         . ''s++(?:'S++'s++){3}'
         . '(?<name>(?>[^(]++|'((?!'d{4}')'s*+$))+)' . ''s++'('
         . '(?<year>'d{4})'                          . '')'s*+$~m';