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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器