I have a MySQL table filled with long texts and I output them splitted in parts. To do so, I manually add [pagebreak] to the texts and it's a pretty cumbersome task I'm craving to avoid.

So here comes a question: Is there a way to split a text after every N paragraph? Each paragraph is indicated by a double CR.

    Yes, it seems posible, but I can't say I know what a "double CR" is or looks like...

      Sorry, should have made it clear from the very beginning: CR stands for "carriage return".

        This spilts $input every double linebreak...

        $parts = preg_split('/\n\n/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
        

        The first part is called $parts[0], the next, $parts[1] and so on. To see how many parts it makes you can use this code:

        echo count($parts);
        

          Thanks a bunch- just the ticket! 🙂 One minor correction though (in case it's of any use to someone else): it should be \r\n\r\n, not \n\n, otherwise it doesn't do the trick.

          $parts = preg_split('/\r\n\r\n/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

            Ok, now I need to output the splitted text. So far I came out with the following (I used a single carriage return to save space):

            $input = '111 - aaaaaaaaaaaaaaaaaaaaaaaaaaaaa
            
            222 - bbbbbbbbbbbbbbbbbbbbbbbbbbb
            
            333 - ccccccccccccccccccccccccccccccccccccc
            
            444 - dddddddddddddddddddddddddddddddd
            
            555 - eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
            
            666 - ffffffffffffffffffffffffffff
            
            777 - gggggggggggggggggggggggggggggggggggggggggggggggg
            
            888 - jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
            
            999 - kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk';
            
            $parts = preg_split('/\r\n/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
            
            $paragraphs_per_page = 2;
            
            // calculate the number of pages
            $page_num = ceil(count($parts) / $paragraphs_per_page);
            
            // now let's test it!
            $page = 4;
            $output = array_slice($parts, ($page - 1) * $paragraphs_per_page, $paragraphs_per_page);
            
            // join the splitted paragraphs and output the text
            echo implode('<br /><br />', $output);

            And the output is:

            777 - gggggggggggggggggggggggggggggggggggggggggggggggg

            888 - jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj

            Works like a charm but I'm still a bit unsure whether or not it's a good solution as the whole thing seems slow to me...

              Write a Reply...