doushupu2521 2014-11-23 16:18
浏览 383
已采纳

用PHP中的字符串获取每一行

I'm trying to read lines from a txt file and return every line that has a certain string on it. In this case I'm looking for "1992"

alt.txt

1223 abcd
1992 dcba
1992 asda

file.php

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            return $line;
        }
    }
    return -1;
}

When I run the php, I get "1992 dcba" as the return, when I want to receive an array with each line. $line[0] would be "1992 dcba" and $line[1] would be "1992 asda". How could I do this?

  • 写回答

3条回答 默认 最新

  • dqs13465424392 2014-11-23 16:21
    关注

    Build an array of all the valid results and return that, rather than simply returning the first result

    function getLineWithString($fileName, $str) {
        $results = array();
        $lines = file($fileName);
        foreach ($lines as $lineNumber => $line) {
            if (strpos($line, $str) !== false) {
                $results[] = $line;
            }
        }
        return $results;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入