在PHP中用strpos跳过空白行

时间:2014-07-28 02:38:43

标签: php

我想读一行,如果是空白,请跳过它。它似乎工作,但我正在阅读的文本文件以三个空行开头,它只跳过其中一个。如何让它跳过文件开头的所有三个空行以及整个文件中的所有其他空行?

$handle = fopen("testlog.log", "r");
if ($handle) {
   while (!feof($handle)) {
      $buffer = fgets($handle, 4096);
      $pos = strpos( $buffer, '/n' );
      if ($pos == false) {
         //do stuff
   }
}

修改

这是完整的代码。我知道我做错了什么......

日志文件中有多个分隔符,有没有办法压缩变量?

日志文件:http://www.castleotwonline.com/crawlerlogs/testlog.log

<?php
$handle = fopen("testlog.log", "r");

$conn = mysql_connect("localhost","user","pass"); 
mysql_select_db("castleot_crawlerlogs",$conn);

    if ($handle) {
        while (!feof($handle))
        {
            $buffer = fgets($handle, 4096);
            $buffer0 = fgets($handle, 4096);
            $buffer1 = fgets($handle, 4096);
            $buffer2 = fgets($handle, 4096);
            $buffer3 = fgets($handle, 4096);
            $buffer4 = fgets($handle, 4096);
            $buffer5 = fgets($handle, 4096);
            $pos = strpos( $buffer, '\n' );
            if ($pos === false) {
                list($version,$versiondata)=explode(" : ",$buffer0);
                list($board,$boarddata)=explode(" --- ",$buffer1);
                list($abilityfriend,$abfdata)=explode(" : ",$buffer2);
                list($abilityenemy,$abedata)=explode(" : ",$buffer3);
                list($mana,$manadata)=explode(" : ",$buffer4);
                list($secret,$secretdata)=explode(": ",$buffer5);
                $secret = "Enemy_secret";
                $sql = "INSERT INTO logtest ($version,$board,$abilityfriend,$abilityenemy,$mana,$secret) VALUES('".$versiondata."','".$boarddata."','".$abfdata."','".$abedata."','".$manadata."','".$secretdata."')";   

                echo $version." : ".$versiondata."<br>".$board." : ".$boarddata."<br>".$abilityfriend." : ".$abfdata."<br>".$abilityenemy." : ".$abedata."<br>".$mana." : ".$manadata."<br>".$secret." : ".$secretdata."<br>";

                mysql_query($sql,$conn) or die(mysql_error());
            }
        }
    }
else {
    echo "File load failed.";
}

fclose($handle);
?>

1 个答案:

答案 0 :(得分:0)

试试这个:

$handle = fopen("testlog.log", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        if (!empty($buffer) && $buffer[0] !== "\n") {
            // do stuff
        }
    }
}