简体   繁体   English

PHP如此多的字符后如何将字符串拆分为两位?

[英]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. 我需要分割的字符串长度为893,004个字符,字符串中的每一行长度为163个字符,我想在100行之后将其拆分。

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, 我尝试在100行之后拆分字符串,

// 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? 我只是想在文件中的100行之后拆分字符串,这怎么容易完成?

I would just use file() to get the file lines as an array or fgets() to extract the file line by line. 我只是使用file()将文件行作为数组或fgets()来逐行提取文件。 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". 目前尚不清楚“100行后拆分字符串”是什么意思。 This adapted example from the docs will write out the file in 100 line chunks (if all lines are 163 chars including the newline). 来自文档的这个改编的示例将以100行的块的形式写出文件(如果所有行都是163个字符,包括换行符)。

$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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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