Find string in file and display lines number - php

I'm new at PHP so I'm need help to build this script.
I have a file.txt file with following lines:
aaaa 1234
bbba 1234
aaaa 1236
cccc 1234
aaaa 1238
dddd 1234
I want to find the line with string "aaaa" and print:
String "aaaa" found 3 times at lines: 1, 3, 5.
And better it can print these lines.
I tried this code:
<?
function find_line_number_by_string($filename, $search, $case_sensitive=false ) {
$line_number = '';
if ($file_handler = fopen($filename, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$search = strtolower($search); //convert file and search string
$line = strtolower($line); //to lowercase
}
//find the string and store it in an array
if(strpos($line, $search) !== false){
$line_number .= $i.",";
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or filename";
}
//if no match found
if(count($line_number)){
return substr($line_number, 0, -1);
}else{
return "No match found";
}
}
$output = find_line_number_by_string('file.txt', 'aaaa');
print "String(s) found in ".$output;
?>
But I dont know how to count total of strings found (3) and print each found line.
Thank in advance.

There are lots of ways to do this that produce the same final result but differ in the specifics.
Assuming that your input is not large enough that you are concerned about loading it in memory all at once, one of the most convenient approaches is to use file to read the file's contents into an array of lines, then preg_grep to filter the array and only keep the matching lines. The resulting array's keys will be line numbers and the values will be whole lines that matched, perfectly fitting your requirements.
Example:
$lines = file('file.txt');
$matches = preg_grep('/aaaa/', $lines);
echo count($matches)." matches found.\n";
foreach ($matches as $line => $contents) {
echo "Line ".($line + 1).": ".$contents."\n";
}

$str = "aaaa";
$handle = fopen("your_file.txt", "r");
if ($handle) {
echo "String '".$str."' found at lines : ";
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
echo implode(", ", $arr_lines).".";
}
UPDATE 2 :
$file = "your_file.txt";
$str = "aaaa;";
$arr = count_line_no($file, $str);
if(count($arr)>0)
{
echo "String '".$str."' found at lines : ".implode(", ", $arr).".";;
}
else
{
echo "String '".$str."' not found in file ";
}
function count_line_no($file, $str)
{
$arr_lines = array();
$handle = fopen("your_file.txt", "r");
if ($handle) {
$count = 0;
$arr_lines = array();
while (($line = fgets($handle)) !== false) {
$count+=1;
if (strpos($line, $str) !== false) {
$arr_lines[] = $count;
}
}
}
return $arr_lines;
}

**Try it for solve your problam **
if(file_exists("file.txt")) // check file is exists
{
$f = fopen("file.txt", "r");
// Read line by line until end of file
$row_count = 0;
while(!feof($f))
{
$row_count += 1;
$row_data = fgets($f);
$findme = 'aaaa';
$pos = strpos($row_data, $findme);
if ($pos !== false)
{
echo "The string '$findme' was found in the string '$row_data'";
echo "<br> and line number is".$row_data;
}
else
{
echo "The string '$findme' was not found ";
}
}
fclose($f);
}

Related

Simple string comparison shows wrong results

It sounds very simple and it should be but I've got some issue and can't find it.
I have a file with words on each line, like
dog
dog
dog
dogfirend
dogandcat
dogcollar
dog-food
The above should display me: 3 (since there are only 3 full matches of dog)
I'm trying to read the file and check how many times the word dog is inside. The problem is that it doesn't count at all and shows 0. This is what I have
$word = "dog";
$count = 0;
$handle = fopen("dogs.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if ($word == $line) {
$count++;
}
}
fclose($handle);
}
The lines in your file are separated by a newline. This newline is included in your $line variable.
From the fgets() manual: "Reading ends when length - 1 bytes have been read, or a newline (which is included in the return value), or an EOF (whichever comes first)."
You need to trim() your $line first, so those characters get removed:
$word = "dog";
$count = 0;
$handle = fopen("dogs.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if ($word == trim($line)) {
$count++;
}
}
fclose($handle);
}
echo $count

How To Open all file in a folder with fopen

I want to know how to search for a string in a folder and display the line in php. I already have a snipset but it dont search in a folder but in ONE file i have tested by replacing /something/sisi.txt by /somthing/* and /something/*.txt .
The snipset:
$searchthis = "jean";
$matches = array();
$handle = #fopen("./something/sisi.txt", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
print_r($matches);
I tested scandir using PHP version 7.4 and it gave expected results.
The reason why I started the index of $i at 2 is because the first two indices refer to "." and ".." which wasn't necessary for the test.
edit: 11/7/2022 -> Additional optional Echo statements have been added to make the separation between files more clear.
The printr from the question code
More info on scandir is here:
https://www.php.net/manual/en/function.scandir.php
<?php
$dir = './something';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
//echo ("<p>Below will be the directory information...</p>");
$L = sizeof($files1);
//print_r($files1);
$results = array();
for($i = 2; $i < $L; $i++) {
//echo "<br>The value of i is: $i";
//echo "<br>The value of files1 at i is:".$files1[$i];
scanFile($files1[$i]);
}
function scanFile($filename) {
//echo("<p>Scanning the file: $filename</p>");
$searchthis = "jean";
$matches = array();
$handle = #fopen("./something/$filename", "r");
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(strpos($buffer, $searchthis) !== FALSE)
$matches[] = $buffer;
}
fclose($handle);
}
for ($i = 0; $i < count($matches); $i++) {
echo "$matches[$i] <br>";
}
}
?>

PHP Read from a CSV-file

I have a simple CSV-file which looks like this:
Value:
AAA
Value:
BBB
Value:
AAA
I want to count the number of times a certain value shows up (e.g. AAA).
To start, I want to get the lines which read "Value:" and just echo the following line "line[$i+1] which would be the corresponding value.
Here's the code:
<?php
$file_handle = fopen("rowa.csv", "r");
$i = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$line[$i] = $line_of_text[0];
if($line[$i] == "Value:"){
echo $line[$i+1]."<br />";
}
$i++;
}
fclose($file_handle);
?>
The outcome should look like this:
AAA
BBB
AAA
Unfortunately, this doesn't work..It just gives me "<*br /">s
If you are printing on command line or a file, you need to use \n instead of <br/>. That only works if your output is HTML. Also every time you want to move two lines. the logic should look like this:
if($line[$i] == "Value:"){
echo $line[$i+1]."\n"; // add a new line
}
$i+=2; // you want to move two lines
This doesn't look like a normal everyday CSV file, but here's an example that should work.
$fh = fopen('rowa.csv', 'r');
$OUT = array();
$C = 0;
while( ! feof($fh) ) {
// read 1 line, trim new line characters.
$line = trim(fgets($fh, 1024));
// skip empty lines
if ( empty($line) ) continue;
// if it's a value line we increase the counter & skip to next line
if( $line === 'Value:' ) {
$C++;
continue;
}
// append contents to array using the counter as an index
$OUT[$C] = $line;
}
fclose($fh);
var_dump($OUT);
This is not a CSV file. The file() command will load the lines of a file into an array. The for loop prints every second line.
$lines = file("thefile.txt");
for ($i = 1; $i < count($lines); $i = $i + 2) {
echo $lines[$i] . "<br/>" . PHP_EOL;
}
As PHP.net example provides, you can use this modified code:
<?php
$count = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (!strcmp($data[$c], 'Value:')) continue;
if (!strcmp($data[$c], 'AAA')) $count++;
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
UPDATE
Try this new code, we use the value as array key and increment the count for that "key".
<?php
$counts = array();
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (strcmp($data[$c], 'Value:'))
{
if (!isset($counts[$data[$c]]))
{
$counts[$data[$c]] = 0;
}
$counts[$data[$c]]++;
}
else
{
// Do something
}
}
}
fclose($handle);
}
var_dump($counts);
?>
You can print the array like this:
foreach ($counts as $key => $count)
{
printf('%s: %d<br/>' . "\n", $key, $count);
}

PHP: Echo next 2 lines after finding one

<?php
$handle = fopen("wqer.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if(preg_match("/aut/i", $line)){
**echo fgets($handle).fgets($handle);**
}
}
} else {
echo "Error loading file.";
}
?>
The textfile wqer.txt looks something like that (but it has 12k lines :D):
bike
*aut*
car
ball
mouse
*aut*
light
house
I want from this script to echo next 2 lines after finding the aut line from this file.
So the output should look like this:
car
ball
light
house
Yep sorry, house should be the last one.
Solved, many thanks to Wrikken, simple solution, I almost feel embarrased :)
$found = 0;
while (($line = fgets($handle)) !== false) {
if(preg_match("/aut/i", $line)){
$found = 2;
continue; // if you don't want "aut" to be printed. remove otherwise.
}
if ($found > 0) {
echo $line;
$found--;
}
}
Add error checking:
$lines = file("wqer.txt", FILE_IGNORE_NEW_LINES);
$lines = array_map('trim', $lines); //in case there are spaces etc. that are not shown
foreach($lines as $key => $val) {
if($val == '*aut*') { //(stripos($val, 'aut') !== false) //to keep similar to how you have it now
echo $lines[$key+1] . "\n" . $lines[$key+2] . "\n";
}
}

Search String and Return Line PHP

I'm trying to search a PHP file for a string and when that string is found I want to return the whole LINE that the string is on. Here is my example code. I'm thinking I would have to use explode but cannot figure that out.
$searchterm = $_GET['q'];
$homepage = file_get_contents('forms.php');
if(strpos($homepage, "$searchterm") !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
Just read the whole file as array of lines using file function.
function getLineWithString($fileName, $str) {
$lines = file($fileName);
foreach ($lines as $lineNumber => $line) {
if (strpos($line, $str) !== false) {
return $line;
}
}
return -1;
}
You can use fgets() function to get the line number.
Something like :
$handle = fopen("forms.php", "r");
$found = false;
if ($handle)
{
$countline = 0;
while (($buffer = fgets($handle, 4096)) !== false)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
$countline++;
}
if (!$found)
echo "$searchterm not found\n";
fclose($handle);
}
If you still want to use file_get_contents(), then do something like :
$homepage = file_get_contents("forms.php");
$exploded_page = explode("\n", $homepage);
$found = false;
for ($i = 0; $i < sizeof($exploded_page); ++$i)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
}
if (!$found)
echo "$searchterm not found\n";
If you use file rather than file_get_contents you can loop through an array line by line searching for the text and then return that element of the array.
PHP file documentation
You want to use the fgets function to pull an individual line out and then search for the
<?PHP
$searchterm = $_GET['q'];
$file_pointer = fopen('forms.php');
while ( ($homepage = fgets($file_pointer)) !== false)
{
if(strpos($homepage, $searchterm) !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
}
fclose($file_pointer)
Here is an answered question about using regular expressions for your task.
Get line number from preg_match_all()
Searching a file and returning the specified line numbers.

Categories