Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
EEQJE2YX 66b375b08fc869632935c9e6a9c7f8da O87IGF8R
c458fb5edb84c54f4dc42804622aa0c5 APLF2J51
B7TSW1ZE 1e9eea56686511e9052e6578b56ae018
EEQJE2YX affb23b07576b88d1e9fea50719fb3b7


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:

<?PHP
$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 :)

like image 496
xZero Avatar asked Nov 04 '13 01:11

xZero


People also ask

How do I search for line numbers in a file?

Use grep -n string file to find the line number without opening the file.

How do I count the number of lines in a PHP file?

$filePath = "test. txt" ; $lines = count (file( $filePath ));

How do you get the line number of a string in a file in Unix?

Use grep -n to get the line number of a match. Ok, so grep -n would return the line that contains the words AND the line number.

How do you check if a file contains a string in PHP?

<? php if( strpos(file_get_contents("./uuids. txt"),$_GET['id']) !== false) { // do stuff } ?>


1 Answers

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;
like image 167
evalarezo Avatar answered Oct 08 '22 18:10

evalarezo