Search String and Return Line PHP

2019-02-15 12:00发布

问题:

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

回答1:

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


回答2:

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



回答3:

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)


回答4:

You can use fgets() function 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(), 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";


回答5:

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.