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

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

本文关键字:最后 单词 五个 获取 文件 get file 使用 contents PHP txt      更新时间:2023-09-26

我正在寻找一种有效的方法,可以在长轮询时使用file_get_contents从.txt文件中读取最后一个单词,例如 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.');
}
?>

应用程序.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", "$2", $code)));
此外,在

分析从服务器检索的代码时,切勿使用 eval。请尝试改用JSON.parse(data)