duanchi8112 2017-08-07 17:24
浏览 135
已采纳

检测文件中的空行

I have a little script that use the function file() for reading the entire file into an array.

$arr = file('file.txt');

The file.txt is structured like this:

john
david

james

So if I debug the array it returns:

array(4) {
  [0]=>
  string(6) "john
"
  [1]=>
  string(7) "david
"
  [2]=>
  string(2) "
"
  [3]=>
  &string(5) "james"
}

I'm trying to find a way to detect the empty line when I analyze every value of the array in a foreach loop:

foreach ($arr as $value) {

I tried with the empty function but nothing.. I also tried with comparing the value with PHP_EOL or , also nothing.

I know that I can avoid empty lines with FILE_IGNORE_NEW_LINES, but I don't need it. I'm just searching for a way to detect this empty lines.

  • 写回答

3条回答 默认 最新

  • dtdr84101 2017-08-07 17:31
    关注

    You should not use file directly, it may result in memory problems. In stead try this.

    <?php
    $file = fopen("test.txt","r");
    
    while(! feof($file))
    {
       // Trim will remove any whitespace prepended/appended
       // Empty line will now result in empty string
       $line = trim(fgets($file));
    }
    
    fclose($file);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏