How do I insert new line every 5 sentences in PHP?

Sample Data:

Sentence1. Sentence2. Sentence3. Sentence4. Sentence5. Sentence6. Sentence7. Sentence8. Sentence9. Sentence10. Sentence11. Sentence12. Sentence13. Sentence14. Sentence15. Sentence16. Sentence17. Sentence18.

Output Data:

Sentence1. Sentence2. Sentence3. Sentence4. Sentence5.

Sentence6. Sentence7. Sentence8. Sentence9. Sentence10.

Sentence11. Sentence12. Sentence13. Sentence14. Sentence15.

Sentence16. Sentence17. Sentence18.

1 Answers

1
Manuel Mannhardt On

So, you can split the full string by dot, then use array_chunk to split the sentences into array which contains 5 sentences each (with the last array containing the reminder of them).

After doing that, you can simply loop over the chunks and implode them again by dot and add your newline (PHP_EOL).

$str = 'Sentence1. Sentence2. Sentence3. Sentence4. Sentence5. Sentence6. Sentence7. Sentence8. Sentence9. Sentence10. Sentence11. Sentence12. Sentence13. Sentence14. Sentence15. Sentence16. Sentence17. Sentence18.';

$sentences = explode('.', $str);
$chunks = array_chunk($sentences, 5);

foreach ($chunks as $chunk) {
    print trim(implode('.', $chunk)) . PHP_EOL;
}

Keep in mind that such questions are way to vague for stackoverflow. This is a board, where you come to with a specific problem within your code.