简体   繁体   中英

Get nth number from a string

I have a very large file with only single line. It contains about 2.6 million of numbers. The file is about 15 mb.

My goal is to find the nth number in this single line string.

I tried to read the file into a string (remember it is single line file). Then I exploded the strings into an array which I ran out of memory. (Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

Am I doing it right? Or is there another easier way to find the nth value in a very large string?

$file = file_get_contents ('a.txt', true);
$array = explode(" ", $file, -1);
echo $array[$nth];

Create a counter variable; read the file using fopen and loop it in a while with feof and fgets (with the desired buffer size); within the loop, check how many spaces are present in the bit you just read (I'm assuming your entries are separated by spaces, it could be commas or whatever); finally increment the counter and go on until you reach the part you want (after a n number of spaces, you have the [n+1]th entry you are looking for).

I include some tested (with a 16 MB file) proof-of-concept code. I don't know if there are better ways to do it; this is the only one that came to my mind and it works. memory_get_usage reports a memory usage of ~8 kb.

<?php

$counter;
$nth = 49959;
$handle = @fopen('numbers.txt', 'r'); // File containing numbers from 1 to 2130829, size ~16 MB.

if ($handle) {
    while (($buffer = fgets($handle, 128)) !== false) {
        $spaces = substr_count($buffer, ' ');

        if ($counter + $spaces > $nth) {
            $numbers = explode(' ', $buffer);
            $key = $nth - $counter;
            echo $numbers[$key]; // print '49959'
            exit;   
        }
        else {
            $counter += $spaces;
        }
    }

    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }

    fclose($handle);
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM