打印文件的内容,直到找到单词hi


print contents of file until found the word hi

我希望程序逐行打印文档内容,同时不到达文件末尾或找到单词hi

问题是当它找到单词hi时,尽管它在位置22,但它什么也不打印。如何解决这个问题?

我的文件包含"Php是一个特例hi。使用迭代解决方案将使用更少的内存。此外,PHP中的函数调用开销很大,因此在可能的情况下最好避免调用函数。这是我的代码

<?php
$contents = file_get_contents('m.txt');
$search_keyword =  'hi';
// check if word is there
$file=fopen("m.txt","r+");
while(!feof($file)&&strpos($contents, $search_keyword) == FALSE)
{
    echo fgets($file)."<br>";
}
?>   

更改此条件

while(!feof($file)&&strpos($contents, $search_keyword) == FALSE)

while(!feof($file)) {
    if(strpos($contents, $search_keyword) === FALSE) {
         echo fgets($file)."<br>";
    } else
         break;
    }
}

你是说逐行打印文件直到找到单词" hi " ?

<?php
$search_keyword = 'hi';
$handle = @fopen("m.txt", "r");
if ( $handle )
{
    // Read file one line at a time
    while ( ($buffer = fgets($handle, 4096)) !== false )
    {
        echo $buffer . '<br />';
        if ( preg_match('/'.$search_keyword.'/i', $subject) )
            break;
    }
    fclose($handle);
}
?>

如果您愿意,可以将preg_match替换为strpos