PHP search and return strings
I am trying to find a PHP file for a string, and when that string is found, I want to return the entire LINE the string is in. Here is my example code. I think I'll have to use an explosion, but can't figure it out.
$searchterm = $_GET['q'];
$homepage = file_get_contents('forms.php');
if(strpos($homepage, "$searchterm") !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
+3
source to share
5 answers
You want to use the fgets function to pull in a single line and then search
<?PHP
$searchterm = $_GET['q'];
$file_pointer = fopen('forms.php');
while ( ($homepage = fgets($file_pointer)) !== false)
{
if(strpos($homepage, $searchterm) !== false)
{
echo "FOUND";
//OUTPUT THE LINE
}else{
echo "NOTFOUND";
}
}
fclose($file_pointer)
+1
source to share
You can use fgets()
to get the line number.
Something like:
$handle = fopen("forms.php", "r");
$found = false;
if ($handle)
{
$linecount = 0;
while (($buffer = fgets($handle, 4096)) !== false)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
$countline++;
}
if (!$found)
echo "$searchterm not found\n";
fclose($handle);
}
If you still want to use file_get_contents()
, do the following:
$homepage = file_get_contents("forms.php");
$exploded_page = explode("\n", $homepage);
$found = false;
for ($i = 0; $i < sizeof($exploded_page); ++$i)
{
if (strpos($buffer, "$searchterm") !== false)
{
echo "Found on line " . $countline + 1 . "\n";
$found = true;
}
}
if (!$found)
echo "$searchterm not found\n";
+1
source to share
Here is the answer to the question about using regular expressions for your task.
Get line number from preg_match_all ()
Search for a file and return the specified line numbers.
+1
source to share