PHP - Find a string in file then show it's line number

自闭症网瘾萝莉.ら 提交于 2019-12-03 06:10:22

An ultra-basic solution could be:

$search      = "1e9eea56686511e9052e6578b56ae018";
$lines       = file('example.txt');
$line_number = false;

while (list($key, $line) = each($lines) and !$line_number) {
   $line_number = (strpos($line, $search) !== FALSE) ? $key + 1 : $line_number;
}

echo $line_number;

A memory-saver version, for larger files:

$search      = "1e9eea56686511e9052e6578b56ae018";
$line_number = false;

if ($handle = fopen("example.txt", "r")) {
   $count = 0;
   while (($line = fgets($handle, 4096)) !== FALSE and !$line_number) {
      $count++;
      $line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
   }
   fclose($handle);
}

echo $line_number;
function get_line_from_hashes($file, $find){
    $file_content = file_get_contents($file);
    $lines = explode("\n", $file_content);

    foreach($lines as $num => $line){
        $pos = strpos($line, $find);
        if($pos !== false)
            return $num + 1
    }
    return false
}

get_line_from_hashes("arquivo.txt", "asdsadas2e3xe3ceQ@E"); //return some number or false case not found.

If you need fast and universal solution that working also for finding line number of multiline text in file, use this:

$file_content = file_get_contents('example.txt');

$content_before_string = strstr($file_content, $string, true);

if (false !== $content_before_string) {
    $line = count(explode(PHP_EOL, $content_before_string));
    die("String $string found at line number: $line");
}

FYI Works only with PHP 5.3.0+.

$pattern = '/1e9eea56686511e9052e6578b56ae018/';
if (preg_match($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
    //PREG_OFFSET_CAPTURE will add offset of the found string to the array of matches
    //now get a substring of the offset length and explode it by \n
    $lineNumber = count(explode("\n", substr($content, 0, $matches[0][1])));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!