xZero xZero - 1 year ago 85
PHP Question

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

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

For example, file example.txt contains few hashes:

APLF2J51 1a79a4d60de6718e8e5b326e338ae533
66b375b08fc869632935c9e6a9c7f8da O87IGF8R

c458fb5edb84c54f4dc42804622aa0c5 APLF2J51

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.

I tried this one:

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

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....

Thanks in advance :)

Answer Source

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) {
      $line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;

echo $line_number;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download