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


Just read the entire file as an array of strings using file

.



function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            return $line;
        }
    }
    return -1;
}

      

+9


source


If you use file

instead file_get_contents

, you can loop through the array line by line looking for text and then return that element of the array.



PHP file documentation

+1


source


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


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


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







All Articles