function getRandLineFromFile($fileName)
{
$hendel = fopen($fileName, 'r+');
if (!$hendel)
return '';
$cLineCount = 0;
$sLineOut = '';
while (!feof($hendel)) {
$cLineCount++;
$sLine = fgets($hendel);
if (rand(1, $cLineCount) == $cLineCount) {
$sLineOut = $sLine;
}
}
return $sLineOut;
}
如果您尝试从字符较小的文件(<)中读取一行,则fgets会在该字符之前修剪字符串,而不是在该行末尾。
文件中的示例字符串:
wordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordword<twotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwotwo
结果:
wordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordwordword