5

我正在尝试在 PHP 文件中搜索字符串,当找到该字符串时,我想返回该字符串所在的整个 LINE。这是我的示例代码。我想我必须使用爆炸,但无法弄清楚。

$searchterm =  $_GET['q'];

$homepage = file_get_contents('forms.php');

 if(strpos($homepage, "$searchterm") !== false)
 {
 echo "FOUND";

 //OUTPUT THE LINE

 }else{

 echo "NOTFOUND";
 }
4

5 回答 5

19

file只需使用函数将整个文件读取为行数组。

function getLineWithString($fileName, $str) {
    $lines = file($fileName);
    foreach ($lines as $lineNumber => $line) {
        if (strpos($line, $str) !== false) {
            return $line;
        }
    }
    return -1;
}
于 2012-03-15T14:48:33.647 回答
2

您可以使用fgets()函数来获取行号。

就像是 :

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

如果您仍想使用file_get_contents(),请执行以下操作:

$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";
于 2012-03-15T14:41:28.223 回答
1

您想使用 fgets 函数拉出单独的行,然后搜索

<?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)
于 2012-03-15T14:40:51.360 回答
1

这是一个关于为您的任务使用正则表达式的已回答问题。

从 preg_match_all() 获取行号

搜索文件并返回指定的行号。

于 2012-03-15T15:00:09.050 回答
1

如果您使用file而不是file_get_contents,您可以逐行遍历数组以搜索文本,然后返回数组的该元素。

PHP 文件文档

于 2012-03-15T14:40:03.463 回答