<?php
/**
* Paginate HTML document results with optional flags.
*
* @param string $html_content The HTML content to paginate.
* @param int $items_per_page The number of items per page. Defaults to 10.
* @param int $page The current page number. Defaults to 1.
* @param array $flags Optional flags to apply to the pagination links.
* Example: ['class' => 'pagination-link', 'active' => 2]
* @return string The paginated HTML output.
*/
function paginateHtml(string $html_content, int $items_per_page = 10, int $page = 1, array $flags = []): string
{
$total_items = count(preg_match_all('/<div[^>]*>/i', $html_content)); // Rough estimate of total items
$total_pages = ceil($total_items / $items_per_page);
if ($total_pages <= 1) {
return $html_content; // No pagination needed
}
$start_index = ($page - 1) * $items_per_page;
$end_index = $start_index + $items_per_page;
$start_html = substr($html_content, $start_index);
$end_html = substr($html_content, $end_index);
$paginated_content = $start_html . $end_html;
$pagination = '';
if ($total_pages > 1) {
$pagination .= '<nav class="pagination">';
if ($page > 1) {
$pagination .= '<a href="?page=' . ($page - 1) . '" class="pagination-link">' . ( $page - 1 ) . '</a>';
}
$pagination .= ' <span class="current-page">' . $page . '</span>';
if ($page < $total_pages) {
$pagination .= ' <a href="?page=' . ($page + 1) . '" class="pagination-link">' . ($page + 1) . '</a>';
}
$pagination .= '</nav>';
}
$output = $pagination . $paginated_content;
//Apply flags to pagination links
foreach ($flags as $key => $value) {
//string interpolation
}
return $output;
}
?>
Add your comment