Search String and Return Line PHP

后端 未结 5 761
傲寒
傲寒 2021-01-05 19:22

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

5条回答
  •  我在风中等你
    2021-01-05 19:23

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

提交回复
热议问题