Haru
Haru

Reputation: 1381

Search String and Return Line PHP

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

Upvotes: 6

Views: 35263

Answers (5)

BMN
BMN

Reputation: 8508

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

Upvotes: 2

martin
martin

Reputation: 96889

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

Upvotes: 20

Thomas Bates
Thomas Bates

Reputation: 677

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.

Upvotes: 1

Hasteur
Hasteur

Reputation: 462

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)

Upvotes: 1

JaredMcAteer
JaredMcAteer

Reputation: 22536

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

Upvotes: 1

Related Questions