简体   繁体   English

如何在PHP中将字符串转换为字符的第n个出现到第n个出现?

[英]How to get string to nth occurrence to nth occurrence of character in PHP?

I am trying to parse a huge string into smaller ones in PHP. 我正在尝试将巨大的字符串解析为PHP中的较小字符串。 I have a string that ends with \\n for each part. 我每个部分都有一个以\\n结尾的字符串。 I want to get the sentence after the 2nd \\n till the 5th \\n . 我想第2次之后获得的句子\\n至第五届\\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. 目的是从第一个$ buffer本身获取一个子字符串,而不创建另一个数组。

I found a good solution using explode and implode and it is fast enough, Here is an example to the code : 我发现了使用explode和implode的一个好的解决方案,它足够快,这是代码示例:

$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. explode将把字符串划分为和平,然后我得到字符在字符串中的第n个出现,strlen然后将获得子字符串的长度,直到第n个出现。

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

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