PHP 使用 file_get_contents 从 .txt 文件中获取最后五个单词

PHP Get last five words from .txt-file using file_get_contents

我正在寻找一种在长轮询时使用 file_get_contents 从 .txt 文件中读取 last 的有效方法,例如 5 个单词。我尝试使用下面的注释代码来解决一个解决方案,但它打破了长轮询——在显示 .txt 文件的完整内容时工作正常。

我也查看了 file_get_contents 的 offset 参数,但我不知道如何在我的代码中对其进行良好(或正常运行)的调整。我想这涉及到首先计算所述 .txt 文件(本身是动态的)中的所有单词,然后以某种方式将该单词数减去 5?可能有比这更简单的解决方案,如果没有,我该如何使用替代解决方案来解决它?

get_data.php

$id = $_COOKIE["currentID"];

$filepath = 'stories/'.$id.'.txt';

if (file_exists($filepath)) {

$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filepath);

while($currentmodif <= $lastmodif){
    sleep(1);
    clearstatcache();
    $currentmodif = filemtime($filepath);
}

        // I've tried:
        // Attempt to getting the last five words of .txt file, does NOT work 
        $str = file_get_contents($filepath);
        $words = explode(' ', $str);
        $last = join(" ", array_slice($words, -5, 5));

  $response = array();
  /*   $response['data'] = file_get_contents($filepath); */  //use if not attempting to get last 5 words
  $response['data'] = $last; //part of "what I've tried"
  $response['timestamp'] = $currentmodif;

echo json_encode($response);  

}

else{
    // if file doesn't exist
    echo('nada data, son.');
}
?>

application.js(上下文)

$(function(){

    $.longpolling({
        pollURL: './get_data.php',
        successFunction: pollSuccess,
        errorFunction: pollError
    });
});

function pollSuccess(data, textStatus, jqXHR){
  var json = eval('(' + data + ')');
  $('#response').html(json['data']);

document.getElementById('notificationsound').play();
console.log('file updated');

}

function pollError(jqXHR, textStatus, errorThrown){
console.log('Long Polling Error: ' + textStatus);
}

为什么不这样做:

$lastfive = explode(" ", trim(preg_replace("/^([\s\S]+)(( ([^ ]+)){5})$/m", "", $code)));

此外,在解析从服务器检索的代码时,您应该永远不要使用eval。请尝试使用 JSON.parse(data)