0

i have a php code that read TXT file and display its content.

i want to allow the user to make a search on any word he want and if its available the system will display it with the line number.

until now i was able to read the text and display it .

i know that i need to read it line by line and stored in variable right or it there any better options?

code

<?php


    $myFile = "test.txt";

    $myFileLink = fopen($myFile, 'r');

    $myFileContents = fread($myFileLink, filesize($myFile));

    while(!feof($myFileContents)) { 
            echo fgets($myFileContents) . "<br />";
        }

    if(isset($_POST["search"]))
    {
        $search =$_POST['name'];
        $myFileContents = str_replace(["\r\n","\r"], "\n",  $myFileContents);
        if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE))
        {
            foreach($matches[1] as $match)
            {
            $line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
            echo "Found $search on $line";
            }
        }
    }


    fclose($myFileLink);

    //echo $myFileContents; 
    ?>

    <html>
        <head>

        </head>
        <body>
         <form action="index.php" method="post">
              <p>enter your string <input type ="text"  id = "idName"  name="name" /></p>
              <p><input type ="Submit" name ="search" value= "Search" /></p>
        </form>
        </body>
    </html>
4
  • file_get_contents if the files are not to big. Commented Dec 23, 2017 at 10:25
  • for bigger files, use fgets until you find a line that contains the search string and keep a running counter of which line you're processing Commented Dec 23, 2017 at 10:26
  • @rickdenhaan now i tried feof () and fgets() functions but it display this error : warrning: feof() expects parameter 1 to be resource, string given in c:\xampp\htdocs\readfiletest\index.php on line 10 warrning: fgets() expects parameter 1 to be resource, string given in c:\xampp\htdocs\readfiletest\index.php on line 11 Commented Dec 23, 2017 at 10:32
  • Those functions need $myFileLink instead of $myFileContents Commented Dec 23, 2017 at 11:51

1 Answer 1

2

Something like this

$myFileContents = file_get_contents($myFileLink);

if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
    print_r($matches);
}

Using Preg match all, and case insensitive flag.

Getting the line number is much harder, for that you will want to do something like this:

$myFileContents = "Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.";

$search = "non proident";

//normalize line endings.
$myFileContents = str_replace(["\r\n","\r"], "\n",  $myFileContents);

    //Enter your code here, enjoy!
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches,PREG_OFFSET_CAPTURE)){

    foreach($matches[1] as $match){
        $line = 1+substr_count(substr($myFileContents,0,$match[1]), "\n");
        echo "Found $search on $line";
    }

}

Outputs

Found non proident on 5

You can see it live here

If it's a large file you can do a similar search as you read each line. Something like this

 $myFileLink = fopen($myFile, 'r');

 $line = 1; 

 while(!feof($myFileLink)) { 
     $myFileContents = fgets($myFileLink);
     if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
        foreach($matches[1] as $match){
           echo "Found $match on $line";
        }
     }
     ++$line;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

i will edit my question and add the new code take a look

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.