1

我尝试读取文本文件中的一些特定行。

我的文本文件是这样的:

#
#  Aliases in this file will NOT be expanded in the header from
#  Mail, but WILL be visible over networks or from /bin/mail.

# Basic system aliases -- these MUST be present.
mailer-daemon:  postmaster
postmaster:     root

# General redirections for pseudo accounts.
bin:            root
nscd:           root
pcap:           root
apache:         root
webalizer:      root

# boite fonctionnelles
# GEMEL
accueil:        demo1,demo2
services:       demo3,demo4
essai:          dan.y.roche@gmail.com

我想收集这条线以在以下情况下对其进行返工:

accueil:        demo1,demo2
services:       demo3,demo4
essai:          dan.y.roche@gmail.com

我可以在评论中找到这一行:# GEMEL

我们做得到 :

if($lines = file($filename)){

    foreach ($lines as $key => $value) {
        if(preg_match("/# GEMEL/", $value))
            for ($i=0; $i < ; $i++) { 
                # code...
            }


}

}

但是双标签并不是很好......解决方案是在找到#GEMEL之后移动指针,但我该怎么做?

4

4 回答 4

1

只是一维循环:

$resultLines = array();
$save = false;

foreach ((array)file($filename) as $key => $value) {
    if (preg_match("/# GEMEL/", $value)) {
        $save = true;
        continue;
    }

    if ($save) {
        $resultLines[] = $value;
    }
}

var_dump($resultLines);

要求在#GEMEL注释之后只存在相关行。如果不是这样,您可以检查下一条评论,然后将其$save再次设置为false

于 2013-05-14T10:16:14.230 回答
0

您可以使用fseek()函数移动到文件流的指针。

您的函数可能如下所示:

<?php
$f=fopen($file,'rb');
$pos = 0;
$blockSize = 8192;
while(!feof($f))
{
    if( $found = strpos( fread($f,$blockSize), '# GEMEL' ) )
    {
         $pos += $found;
         break;
    }
    else
    {
         $pos += $blockSize ;
    }
}
// now you can go to $pos
fseek( $f, $pos );
// read line you need
// ...


fclose($f);
?>
于 2013-05-14T10:17:12.047 回答
0
if($lines = file($filename)){
    foreach ($lines as $key => $value) {
        if(preg_match("/# GEMEL/", $value)) { 
            $myAccueil = $lines[$key+1];
            $myServices = $lines[$key+2];
            $myEssai = $lines[$key+3]; 
            break;       
        }
    }
} 
于 2013-05-14T10:20:06.000 回答
0

您不必使用preg_match. 我推荐你strpos

<?php

$collection = '';
$count = 0;

$fp = fopen($filename,'rb') or die('Error');
while (($line = fgets($fp)) !== false) {
    if ($count === 0 && strpos($line, '# GAMEL') === 0) {
        $count++;
        continue;
    }
    if ($count >= 1 && $count <= 3) {
        $collection .= $line;
    }
    if ($count === 3)
        $count = 0;
}

echo $collection;

如果你想$collection作为一个数组,

<?php

$collection = array();
$count = 0;

$fp = fopen($filename,'rb') or die('Error');
while (($line = fgets($fp)) !== false) {
    if ($count === 0 && strpos($line, '# GAMEL') === 0) {
        $count++;
        continue;
    }
    if ($count >= 1 && $count <= 3) {
        $collection[] = rtrim($line);
    }
    if ($count === 3)
        $count = 0;
}

print_r($collection);
于 2013-05-14T10:21:28.037 回答