douke6027 2011-02-07 21:15
浏览 168
已采纳

需要在文本文件匹配字符串中获取行号

I need to get the line number of a text file using PHP. The line I need is "WANT THIS LINE".

I tried using file() to put the file lines in an array and search using array_search() but it won't return the line number. In this example I would need to return 3 as the line number.

$file = file("file.txt");
$key = array_search("WANT", $file);
echo $key;

Text File:

First Line of Code
Some Other Line
WANT THIS LINE
Last Line
  • 写回答

2条回答 默认 最新

  • duanpiangeng8958 2011-02-07 21:18
    关注

    array_search() is looking for an exact match. You'll need to loop through the array entries looking for a partial match

    $key = 'WANT';
    $found = false;
    foreach ($file as $lineNumber => $line) {
        if (strpos($line,$key) !== false) {
           $found = true;
           $lineNumber++;
           break;
        }
    }
    if ($found) {
       echo "Found at line $lineNumber";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大