1. <?php
  2. /**
  3. * Paginate HTML document results with optional flags.
  4. *
  5. * @param string $html_content The HTML content to paginate.
  6. * @param int $items_per_page The number of items per page. Defaults to 10.
  7. * @param int $page The current page number. Defaults to 1.
  8. * @param array $flags Optional flags to apply to the pagination links.
  9. * Example: ['class' => 'pagination-link', 'active' => 2]
  10. * @return string The paginated HTML output.
  11. */
  12. function paginateHtml(string $html_content, int $items_per_page = 10, int $page = 1, array $flags = []): string
  13. {
  14. $total_items = count(preg_match_all('/<div[^>]*>/i', $html_content)); // Rough estimate of total items
  15. $total_pages = ceil($total_items / $items_per_page);
  16. if ($total_pages <= 1) {
  17. return $html_content; // No pagination needed
  18. }
  19. $start_index = ($page - 1) * $items_per_page;
  20. $end_index = $start_index + $items_per_page;
  21. $start_html = substr($html_content, $start_index);
  22. $end_html = substr($html_content, $end_index);
  23. $paginated_content = $start_html . $end_html;
  24. $pagination = '';
  25. if ($total_pages > 1) {
  26. $pagination .= '<nav class="pagination">';
  27. if ($page > 1) {
  28. $pagination .= '<a href="?page=' . ($page - 1) . '" class="pagination-link">' . ( $page - 1 ) . '</a>';
  29. }
  30. $pagination .= ' <span class="current-page">' . $page . '</span>';
  31. if ($page < $total_pages) {
  32. $pagination .= ' <a href="?page=' . ($page + 1) . '" class="pagination-link">' . ($page + 1) . '</a>';
  33. }
  34. $pagination .= '</nav>';
  35. }
  36. $output = $pagination . $paginated_content;
  37. //Apply flags to pagination links
  38. foreach ($flags as $key => $value) {
  39. //string interpolation
  40. }
  41. return $output;
  42. }
  43. ?>

Add your comment