title: how to search for a string in text file using PHP
body: <p>i have a php code that read TXT file  and display its content.</p>
  
  <p>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.</p>
  
  <p>until now i was able to read the text and display it .</p>
  
  <p>i know that i need to read it line by line and stored in variable right or it there any better options?</p>
  
  <h1>code</h1>
  
  <pre><code>&lt;?php
  
  
      $myFile = "test.txt";
  
      $myFileLink = fopen($myFile, 'r');
  
      $myFileContents = fread($myFileLink, filesize($myFile));
  
      while(!feof($myFileContents)) { 
              echo fgets($myFileContents) . "&lt;br /&gt;";
          }
  
      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; 
      ?&gt;
  
      &lt;html&gt;
          &lt;head&gt;
  
          &lt;/head&gt;
          &lt;body&gt;
           &lt;form action="index.php" method="post"&gt;
                &lt;p&gt;enter your string &lt;input type ="text"  id = "idName"  name="name" /&gt;&lt;/p&gt;
                &lt;p&gt;&lt;input type ="Submit" name ="search" value= "Search" /&gt;&lt;/p&gt;
          &lt;/form&gt;
          &lt;/body&gt;
      &lt;/html&gt;
  </code></pre>