6

I'm trying to search a PHP file for a string and when that string is found I want to return the whole LINE that the string is on. Here is my example code. I'm thinking I would have to use explode but cannot figure that out.

$searchterm =  $_GET['q'];

$homepage = file_get_contents('forms.php');

 if(strpos($homepage, "$searchterm") !== false)
 {
 echo "FOUND";

 //OUTPUT THE LINE

 }else{

 echo "NOTFOUND";
 }
Haru
  • 1,361
  • 2
  • 15
  • 40

5 Answers5

20

Just read the whole file as array of lines using file function.

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            return $line;
        }
    }
    return -1;
}
martin
  • 93,354
  • 25
  • 191
  • 226
2

You can use fgets() function to get the line number.

Something like :

$handle = fopen("forms.php", "r");
$found = false;
if ($handle) 
{
    $countline = 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(), then do something like :

$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";
Dakotah
  • 3
  • 2
BMN
  • 8,253
  • 14
  • 48
  • 80
1

If you use file rather than file_get_contents you can loop through an array line by line searching for the text and then return that element of the array.

PHP file documentation

JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
1

You want to use the fgets function to pull an individual line out and then search for the

<?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)
Hasteur
  • 462
  • 2
  • 6
1

Here is an answered question about using regular expressions for your task.

Get line number from preg_match_all()

Searching a file and returning the specified line numbers.

Community
  • 1
  • 1
Thomas Bates
  • 677
  • 4
  • 15