Paginate Paragraphs - Show Certain Number Of Paragraphs Per Page


/ Published in: PHP
Save to your folder(s)

I wrote this really quick and dirty script to paginate a very large chunk of text. A client site was setup with the understanding their about page would consist of 5-6 paragraphs but their biography ended up being 60 paragraphs. At the end of the day instead of breaking segments out into separate pages as stored in the database I kept it intact (including the way they edit it in the CMS) but this simple function paginates it only showing a certain number of paragraphs at a time.

Please email code -at- aristoworks.com if you need some clarification on how to use this.


Copy this code and paste it in your HTML
  1. function paraPag($data) {
  2.  
  3. $chars = "<p> </p>"; // CHARACTERS TO REMOVE FROM LEFT AND RIGHT OF ORIGINAL TEXT
  4.  
  5. $text = trim($data, $chars);
  6.  
  7. $delimiter = "<br /><br />"; // COULD BE <BR><BR>, \n\r,
  8. OR ANYTHING THAT APPEARS BETWEEN YOUR PARAGRAPHS
  9.  
  10. $paragraphs = explode($delimiter, $text);
  11.  
  12. $count = count($paragraphs); // GET THE COUNT OF PARAGRAPHS
  13.  
  14. $num_page = 10; // THE NUMBER OF PARAGRAPHS YOU WANT DISPLAYED ON EACH PAGE
  15.  
  16. $pages = ceil($count / $num_page); // GET THE NUMBER OF PAGES TOTAL
  17.  
  18. $output = ''; // INITIATE THE VARIABLE
  19.  
  20. // SET THE PAGE NUMBER
  21. if(isset($_GET['page'])) {
  22. $page = $_GET['page'];
  23. } else {
  24. $page = 1;
  25. }
  26.  
  27. $start = ($page * $num_page) - $num_page;
  28.  
  29. $end = ($page * $num_page) - 1;
  30.  
  31. // PRINT THE PAGE CONTENTS
  32. for($i=$start; $i<=$end; $i++) {
  33.  
  34. if($i< $count) {
  35. $output .= "<p>".$paragraphs[$i]."</p>\n";
  36. }
  37.  
  38. }
  39.  
  40. // PRINT OUT THE PAGE NUMBERS
  41. for($i=1; $i<=$pages; $i++) {
  42.  
  43. if($i == $page) {
  44. $class = "class=\"activePage\"";
  45. } else {
  46. $class = 'class="page"';
  47. }
  48.  
  49. $output .= "<a $class href=\"?page=$i\">$i</a> ";
  50.  
  51. }
  52.  
  53. return $output;
  54.  
  55. }

URL: http://www.aristoworks.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.