2

我希望程序逐行打印文档内容,而既没有到达文件末尾也没有找到单词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>";

}
?>   
4

2 回答 2

0

改变这个条件

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

while(!feof($file)) {
    if(strpos($contents, $search_keyword) === FALSE) {
         echo fgets($file)."<br>";
    } else
         break;
    }
}
于 2013-04-29T04:47:47.057 回答
0

您的意思是逐行打印文件,直到找到单词'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_matchto 。strpos

于 2013-04-29T04:56:30.980 回答