0

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.

2
  • Please show us example code of methods you have already tried. Commented Aug 19, 2014 at 10:12
  • Comments are not for extended discussion; this conversation has been moved to chat. Commented Aug 19, 2014 at 10:55

3 Answers 3

3

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";
}
Sign up to request clarification or add additional context in comments.

Comments

-1
$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;
}

Comments

-1

**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);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.