Search String and Return Line PHP

Haru picture Haru · Mar 15, 2012 · Viewed 29.7k times · Source

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";
 }

Answer

martin picture martin · Mar 15, 2012

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;
}