简体   繁体   中英

How to split a string into two bits after so many characters PHP?

I am looking for a very efficient way of splitting a string and returning both parts.

The string I need to split is 893,004 characters long, each line in the string is 163 characters long, and I want to split it after 100 lines.

A quick representation of the string file that is gotten from a file using regex,

'/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' // 163 characters
'/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' // 163 characters
'/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' '/[a-z0-9]{40}/i' // 163 characters

And so on and on lol,

My attempt at splitting the string after 100 lines,

// FILE CONTENTS
$content = file_get_contents($file);
// GET PARSER GXDE
$split = preg_split('/^[a-z0-9\s]{16300}$/i', $content, 1); // REGEX DOESNT WORK
var_dump($split[0]);

I am just looking to split the string after 100 lines in the file how is this easily done?

I would just use file() to get the file lines as an array or fgets() to extract the file line by line. This would then allow you to use a simple counter to break the file at the appropriate number of lines.

You really shouldn't be using a regex if you don't have to. A regex is a relatively expensive operation and if you're using a regex to get a fixed-length string that's just a waste of processing.

It's not clear what you mean by "split the string after 100 lines". This adapted example from the docs will write out the file in 100 line chunks (if all lines are 163 chars including the newline).

$handle = @fopen("/inputfile.txt", "r");
if ($handle) {
    $i = 0;
    while (($buffer = fgets($handle, 163000)) !== false) {
        $i++;
        file_put_contents("chunk$i.txt", $buffer);
    }
    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