从两个标记之间的行创建数组

时间:2012-03-19 19:39:24

标签: php regex

这段代码有什么问题:
我需要从令牌之间的行创建一个数组:START正在启动而END正在结束令牌;
我有这种类型的文本文件:

 123-456-6541 (P) 
 you got page one
 second line
 third line
 END
 123-456-6541 (P) 
 you got page one
 second line
 another line 
 END
这是php代码;它应该继续将行插入数组,直到它到达第二个令牌:

        <?php
        $fh = fopen('text2.txt','r');
        while ($line = fgets($fh)) {    $lines[] = $line; }

        $active = false;
        $temp = "";
        $result = array();

            for ($i = 0; $i < count ($lines); $i++ )
            {
                     $line = $lines[$i];

                       if  ( strpos ( $line , ' 123-456-6541 (P)' ) !== false )
                                 {  
                                            $result[]= $line;
                                            $active = true;
                                 }      
                            if (strpos($line, 'END') !== false ) {
                                                      $active = false;
                                } 

            if ($active)
                $result[] = $line; 
            }   

                    print_r ( $result );

以下是理想的结果:

        Array
(
[0] => you got page one
       second line
       third line

[1] => you got page one 
       second line
       another line
 )

2 个答案:

答案 0 :(得分:0)

对于strpos ( $line , 'TOK1' ) !== false

strpos ( $line , 'TOK' ) !== falseTOK1都适用。在将其设置为true后,您将活动设置为false。 (此信息不再有效,因为问题已编辑)

有了这些新信息,您应该能够制定解决方案......

修改

如果我打算这样做,它会看起来像这样。当然,这并没有考虑很多因素,但这是一个开始,我不知道你的最终目标是什么:

我再次编辑代码以匹配您的新文件布局......

$lines = file('text2.txt');

$result = array();
$i      = 0;
foreach($lines as $line){
    if(strpos($line, 'END') !== false){
        $i++;
    } else {
        $result[$i][] = $line;
    }
}

print_r($result);

答案 1 :(得分:0)

编辑:自源数据示例更改后重写

$t = <<< EOF
 123-456-6541 (P)
 you got page one
 second line
 third line
 END
 123-456-6541 (P)
 you got page one
 second line
 aanother line
 END

EOF;

preg_match_all( "/[0-9]{3}-[0-9]{3}-[0-9]{4}[ ]+\(P\)(.*)END/msU", $t, $r );

print_r( $r );  

这将匹配电话号码模式并吐出以下内容:

Array
(
    [0] => Array
        (
            [0] => 123-456-6541 (P)
 you got page one
 second line
 third line
 END
            [1] => 123-456-6541 (P)
 you got page one
 second line
 aanother line
 END
        )

    [1] => Array
        (
            [0] => 
 you got page one
 second line
 third line

            [1] => 
 you got page one
 second line
 aanother line

        )

)