實例代碼:
復制代碼 代碼如下:
<?php
/**
* **********************************************************
* Read Me
* 文章分頁
*
* 分頁方式,可以按字數分頁,按換行分頁,按特殊標記分頁等
* 其實實現思路是一樣的,只是將其按一定規律放入一個數組
* 然後根據 url 傳入的參數取得某個片段即可
* 大家完全可以寫一個功能強大的函數保存起來以備不時之需
*
* 題外話:很多編輯器都有插入分頁按鈕,利用插入的代碼可顯示分頁
*
* filename: page.php
* charset: UTF-8
* create date: 2012-5-16
* **********************************************************
* @author itbdw <[email protected]>
* @copyright (C) 2011-2012 itbdw
* @link http://weibo.com/itbudaoweng
*/
header('Content-Type:text/html; charset=utf-8');
?>
<?php
$title = 'Pagination Test';
//需要分頁的數據
$data = <<<DATA
Hey, guys. I am here to test if it is working.
This pagination is very simple, isn't it?<!--pagination-->
And I tried to use different method to page it.
Can you see it?
DATA;
//當前文章頁
$page = 0;
//初始文章長度
$length = 0;
//分頁長度
$perpage = 160;
//顯示在頁面的代碼
$link = '';
//分割後的數組
$strArr = array();
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
$length = strlen($data);
//按字數分割
// $str = str_split($data, $perpage);
//按字符分割
$delimiter = "\n";
// $delimiter = '<--pagination-->';
$strArr = explode($delimiter, $data);
$strNum = count($strArr);
$content = $strArr[$page];
if ($strNum > 1) {
if ($page != 0) {
$link .= '<a href="?page=0">首頁</a>';
} else {
$link .= '<span>首頁</span>';
}
for ($n = 0; $n < $strNum; $n++) {
if ($n == $page) {
$link .= '<span>' . ($n + 1) . '</span>';
} else {
$link .= "<a href='?page={$n}'>" . ($n + 1) . "</a>";
}
}
$link .= '';
if ($page != ($strNum - 1)) {
$link .= "<a href='?page=" . ($strNum - 1) . "'>尾頁</a>";
} else {
$link .= '<span>尾頁</span>';
}
}
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<style type="text/css">
body {
font-family: '微軟雅黑';
}
.link a, span {
margin: 1px;
padding: 1px;
}
.link span {
color: #777;
}
.link a {
color: #26A2DA;
text-decoration: none;
}
</style>
<title>測試文章分頁</title>
</head>
<body>
<h1><?php echo $title; ?></h1>
<p><?php echo $content; ?></p>
<hr />
<p class="link"><?php echo $link; ?></p>
</body>
</html>