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(["
",""], "
", $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]), "
");
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>