【问题标题】:PHP Get last five words from .txt-file using file_get_contentsPHP 使用 file_get_contents 从 .txt 文件中获取最后五个单词
【发布时间】:2015-02-01 18:47:28
【问题描述】:

我正在寻找一种在长轮询时使用 file_get_contents 从 .txt 文件中读取 last 的有效方法。我尝试使用下面注释的代码来解决解决方案,但它破坏了长轮询 - 在显示 .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);
}

【问题讨论】:

    标签: javascript php string output file-get-contents


    【解决方案1】:

    为什么不这样做:

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

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

    【讨论】:

    • 感谢关于不使用 eval 的建议。你的例子几乎完美无缺,它确实只显示了最后五个单词,这正是我想要实现的——但它也删除了单词之间的所有空格; This is a test to see what happens 变为 testtoseewhathappens。另外,我很好奇"$2" 在这种情况下是什么?
    • 尝试从上面的示例中删除 explode 函数。这将输出一个字符串,然后您可以使用 javascript data.split(' ') 而不是输出和解析 JSON 对象。 $2 指的是 preg_replace 中正则表达式模式中的第二个匹配项。该模式匹配字符串 ^ 开头的任何字符 ([\s\S]),然后是一组五个单词 ((...){5}),其中一个开头空格和单词匹配 `([a-zA-Z]+)` 直到字符串$ 的结尾。 Have a read about regular expressions in PHP.
    • 啊,我明白了。那我一定会看看表达式的使用。最后一件事,我注意到您提供的原始代码在收到包含变音符号(例如 å ä ö)的字符串时会中断,这也是由于使用了表达式(因为它可能会在 . txt 文件)?
    • 哎呀!已更新代码。 [a-zA-Z] 已更改为 [^ ]
    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 2012-07-19
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多