Search String and Return Line PHP

后端 未结 5 713
傲寒
傲寒 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";
    
    0 讨论(0)
  • 2021-01-05 19:23

    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.

    0 讨论(0)
  • 2021-01-05 19:29

    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;
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-05 19:46

    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)
    
    0 讨论(0)
提交回复
热议问题