PHP - 在文件中查找一个字符串,然后显示它的行号

2022-01-20 00:00:00 string line numbers find php

我有一个应用程序需要打开文件,然后在其中找到字符串,并打印找到字符串的行号.

I have an application which needs to open the file, then find string in it, and print a line number where is string found.

例如,文件 example.txt 包含少量哈希:

For example, file example.txt contains few hashes:

APLF2J51 1a79a4d60de6718e8e5b326e338ae533
EEQJE2YX66b375b08fc869632935c9e6a9c7f8da O87IGF8R
c458fb5edb84c54f4dc42804622aa0c5 APLF2J51
B7TSW1ZE1e9eea56686511e9052e6578b56ae018
EEQJE2YXaffb23b07576b88d1e9fea50719fb3b7

APLF2J51 1a79a4d60de6718e8e5b326e338ae533
EEQJE2YX 66b375b08fc869632935c9e6a9c7f8da O87IGF8R
c458fb5edb84c54f4dc42804622aa0c5 APLF2J51
B7TSW1ZE 1e9eea56686511e9052e6578b56ae018
EEQJE2YX affb23b07576b88d1e9fea50719fb3b7


所以,我想用 PHP 搜索1e9eea56686511e9052e6578b56ae018"并打印出它的行号,在本例中为 4.


So, I want to PHP search for "1e9eea56686511e9052e6578b56ae018" and print out its line number, in this case 4.

请注意,文件中不会有多个哈希值.

Please note that there are will not be multiple hashes in file.

我在互联网上找到了一些代码,但似乎都没有.

I found a few codes over Internet, but none seem to work.

我试过这个:

<?PHP
$string = "1e9eea56686511e9052e6578b56ae018"; 
$data   = file_get_contents("example.txt"); 
$data   = explode("
", $data); 
for ($line = 0; $line < count($data); $line++) { 
if (strpos($data[$line], $string) >= 0) { 
die("String $string found at line number: $line"); 
} 
} 
?>

它只是说在第 0 行找到了字符串......这是不正确的......

It just says that string is found at line 0.... Which is not correct....

最终申请比这复杂得多...找到行号后,它应该替换其他字符串,并将更改保存到文件中,然后进行进一步处理....

Final application is much more complex than that... After it founds line number, it should replace string which something else, and save changes to file, then goes further processing....

提前致谢:)

推荐答案

一个超基本的解决方案可能是:

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;

相关文章