Php 从末尾解析文件

Php 从末尾解析文件,php,cakephp-1.3,Php,Cakephp 1.3,我有一个文本文件,里面有这样的信息 ##john##eva##shawn##roger##henry##david 我想知道最后的姓氏,然后休息。 我是怎么做到的 谢谢将文件加载到变量后,您可以使用找到“##”的最后一次出现,然后在使用时从那里读取。大文件解决方案: $handle = fopen("myfile.txt", "r"); $file_size = filesize("myfile.txt"); $seek_position = -1024; fseek($handle, $s

我有一个文本文件,里面有这样的信息

##john##eva##shawn##roger##henry##david
我想知道最后的姓氏,然后休息。 我是怎么做到的
谢谢

将文件加载到变量后,您可以使用找到“##”的最后一次出现,然后在使用时从那里读取。

大文件解决方案:

$handle = fopen("myfile.txt", "r");
$file_size = filesize("myfile.txt");

$seek_position = -1024;
fseek($handle, $seek_position, SEEK_END);
while(strpos($data = fread($handle, abs($seek_position)), '##') === false){
    $seek_position = $seek_position - 1024;
    if(abs($seek_position) > $file_size)
        break;

    fseek($handle, $seek_position, SEEK_END);
}
$val = substr(2, $data);
$file_contents = get_file_contents($file_location);
$array = explode('##', $file_contents);
$val = $array[end(array_keys($array))];
unset($array);

小文件解决方案:

$handle = fopen("myfile.txt", "r");
$file_size = filesize("myfile.txt");

$seek_position = -1024;
fseek($handle, $seek_position, SEEK_END);
while(strpos($data = fread($handle, abs($seek_position)), '##') === false){
    $seek_position = $seek_position - 1024;
    if(abs($seek_position) > $file_size)
        break;

    fseek($handle, $seek_position, SEEK_END);
}
$val = substr(2, $data);
$file_contents = get_file_contents($file_location);
$array = explode('##', $file_contents);
$val = $array[end(array_keys($array))];
unset($array);

使用
fseek
快速跳转到文件末尾

$handle = fopen("myfile.txt", "r");
fseek($handle, -20, SEEK_END);
$bytes = fread($handle, 20);

将读取文件的最后20个字节(并跳过其余字节)。

您可以将整个字符串分解为一个数组,然后使用php的end()函数,如下所示:

// define our string
$string = "##john##eva##shawn##roger##henry##david";
// use the explode function to create an array using the delimiter ##
$array = explode("##", "##john##eva##shawn##roger##henry##david");
// print last object of the array using the php's end function
print end($array);

除非您知道姓氏的长度,或者至少知道姓氏的最大长度,否则您不能真正跳到文件的末尾并拉出名称

您需要做的是将文件读入缓冲区,并使用explode()和“###”之类的方法对其进行解析,然后获取返回数组的最后一个元素,或者使用strpos()查找“##”的最后一个出现点并从那里继续读取

下面是一个使用explode的示例

$sFileName = "file.txt";

$sContents = file_get_contents($sFileName);

$aNames = explode("##", $sContents);

$sLastName = $aNames[count($aNames)-1]; 

如果您的文件大小超过几兆字节,这将不起作用。当然,这取决于您的PHP内存限制。此外,示例中提供的文本很小,没有提到MB/GB的信息谁将4GB的信息存储在文本文件中进行随机搜索=D如果我正在开发他们的软件和托管他们的服务,他们不会在这里,我修改了我的答案,扔给我GBST。如果你的文件超过几兆字节,这将不起作用。他没有指定它是一个大文件或任何东西。答案与问题中给出的例子相符。他提到了“ingnore rest”,所以我假设一个
fseek
。您的方法不会忽略其余部分。您需要猜测姓氏的大小。不,您可以增加(或减少?)偏移量,直到找到
。向后阅读和向前阅读没有什么不同。当然,我的代码需要修改才能做到这一点,但我不会为此获得报酬;)如果你的答案是这样的,那将是完美的答案。可能需要对其进行编辑以使其完全适合。您可以跳到结尾并向后阅读,直到找到一个