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