I am trying to parse a huge string into smaller ones in PHP. I have a string that ends with \\n
for each part. I want to get the sentence after the 2nd \\n
till the 5th \\n
.
I managed to that in a way but since the string that I'm dealing with is huge, it takes loads of time. This is the method I used:
$arrayBuffer = explode("\n", $buffer);
for($i = 0; $i < $NumOfRequests; $i++) {
$tmpBuffer = "";
for($j = $i * $NumOfAllowedRows; $j < ($i + 1) * $NumOfAllowedRows; $j++) {
// stop the loop if it reached the last cell of arrayBuffer, to avoid Index Out Of Bound Exception
if($j === $arrayBuffer[count($arrayBuffer)]){
break;
}
$tmpBuffer = $tmpBuffer . $arrayBuffer[$j] . "\n";
}
// do something with the tmpBuffer
}
The purpose is to take a substring from the first $buffer itself without creating another array.
I found a good solution using explode and implode and it is fast enough, Here is an example to the code :
$buffer = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\n"; // enter file path here
for($i = 0; $i < 5 ; $i++){
$arr = explode("\n", $buffer);
//strlen(implode("\n", array_slice($arr, 0, 6)));
$position = (strlen(implode("\n", array_slice($arr, 0, 3))));
$tmpBuffer = substr($buffer,0,$position);
$buffer = substr($buffer, $position);
error_log("tmpbuffer : ".$tmpBuffer).PHP_EOL;
error_log("buffer : " . $buffer).PHP_EOL;
explode will divide the string into peaces, then I get the character's nth occurrence in the string, strlen will then get the length of the sub-string till the nth occurrence.
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.