在文章內容中植入特殊標記(如 `
p0
`、`p1
`...),PHP 讀取時解析標記位元組偏移,依 URL 參數 `ptag` 顯示對應區段。適合內容固定、編輯器可插入標記的場景。CREATE TABLE article (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255),
content MEDIUMTEXT, -- 含 p0, p1... 標記
created_at DATETIME
);
<?php
// 1. 取得文章
$stmt = $pdo->prepare('SELECT content FROM article WHERE id = ?');
$stmt->execute([41]);
$row = $stmt->fetch();
$content = $row['content'];
// 2. 掃描標記位置
$tags = [];
$tag = 0;
while (($pos = strpos($content, "p$tag")) !== false) {
$tags[] = $pos;
$tag++;
}
$totalPages = count($tags);
// 3. 判斷要顯示第幾頁
$ptag = isset($_GET['ptag']) ? (int)$_GET['ptag'] : 0;
$ptag = max(0, min($ptag, $totalPages - 1));
// 4. 截取內容
if ($totalPages === 0) {
$display = $content; // 無標記,全文顯示
} elseif ($ptag === 0) {
$display = substr($content, 0, $tags[0]);
} else {
$start = $tags[$ptag - 1] + 2; // 跳過標記本身
$end = $tags[$ptag];
$display = substr($content, $start, $end - $start);
}
// 5. 輸出內容
echo $display;
// 6. 產生分頁導航
if ($totalPages > 0) {
echo '<div class="pagination">';
for ($i = 0; $i < $totalPages; $i++) {
$class = ($i === $ptag) ? ' class="active"' : '';
echo "<a href=\"?ptag=$i\"$class>" . ($i + 1) . "</a> ";
}
echo '</div>';
}
?>
| 優點 | 缺點 |
|---|---|
| 邏輯簡單、無需額外欄位 | 需人工在內容插入標記,維護成本高 |
| 分頁斷點可精確控制(段落、圖片間) | 不支援自動依字數/高度分頁 |
| 資料庫只存單一 content 欄位 | 標記若被誤刪會導致分頁錯亂 |