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

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样