php中長文章分頁顯示實現代碼

來源:互聯網
上載者:User

歡迎交流!實現代碼如下: 複製代碼 代碼如下:<?php include('include/config.php'); ?>
<?php
/**
*Author:烏鳥heart
*實現長文章分頁的代碼
*原理:
*利用一個數組來記錄文章每一頁(用p0、p1、p2...做手動標記)的起始位元組數,然後通過利用php函數操作這個數組去顯示分頁後的文章。分頁顯示,傳遞ptag(與tag的值一樣)值。
*利用到的php函數:
*1、strlen("字串") - Returns the length of the given string. - 返回字串的位元組總數。
*2、strpos("字串","匹配字元") - Returns the numeric position of the first occurrence of needle in the haystack string. - 返回字串中出現的第一個相匹配的字元所在的位元組序數。
*3、substr("字串","起始位置","終止位置") - substr() returns the portion of string specified by the start and length parameters. - 返回字串中指定起止位置的若干字元。
*/
$sql = "select * from article where id = 41";//定義sql語句,返回id為41的內容
$result = mysql_query($sql);//執行sql語句,返回結果集
$row = mysql_fetch_array($result);//以數組的形式從屬記錄集返回
$content = $row['content'];//把文章賦給變數$content
$articleCounts = strlen($content);//返回$content(文章)的總位元組數
$isTrue = true;//迴圈標記
$tag = 0;//分頁標記、數組下標
echo "位元組總數:".$articleCounts."<br>";//測試資訊
//尋找標記“ptag”,並把其位置(所在的位元組數)賦給數組array[]------------------------------------------
while($isTrue){
$startAt = strpos($content,"p".$tag);//得到相應ptag的位元組序數
if($startAt != false){ //如果有標記(傳回值不是false),則記錄位置
$array[$tag++] = $startAt;
}else{ //如果沒有標記,則將數組array[0]賦值'\0'
$array[$tag] = '\0';
$isTrue = false;
}
}
//迴圈輸出標記位置-------------------------------------------------------------測試資訊
for($i = 0; $i < $tag; $i++){
echo $array[$i]."<br>";
}
echo "------------------------------ <br>";
//輸出內容---------------------------------------------------------------------
if($array[0] == '\0'){ //判斷是否有標記
echo $content; //沒有標記的情況,單頁顯示
}else{ //有標記的情況,分頁顯示
//輸出分頁內容
if( isset($_GET['ptag']) ){ //判斷是否有ptag值傳遞,有則顯示第 ptag+1 頁,否則顯示第一頁(ptag=0)
$ptag = $_GET['ptag']; //把ptag的值賦給變數$ptag
if($ptag < $tag){ //判斷參數是否有誤
echo "有值傳遞,顯示第".($ptag+1)."頁<br>"; //測試資訊
echo "值為:".$ptag."<br>"; //測試資訊
echo substr($content,$array[$ptag - 1] + 2,$array[$ptag] - $array[$ptag - 1] - 2);//顯示ptag+1頁的內容
}else{echo "參數有誤";}
}
else{ //沒有ptag值傳遞的情況,顯示第一頁(ptag=0)
echo "無值傳遞,顯示第1頁<br>"; //測試資訊
echo substr($content,0,$array[0] - 1);//顯示第一頁的內容
}
}
//迴圈顯示頁數連結-------------------------------------------------------------
if($array[0] != '\0'){ //在有手動標記的情況下才顯示頁數連結
for($i = 0;$i < $tag;$i++){
if($ptag == $i){ //如果是本頁,則粗體顯示
$pager .= " <a href='test.php?ptag=$i'><b>".($i+1)."</b></a> ";
}else{ //不是本頁
$pager .= " <a href='test.php?ptag=$i'>".($i+1)."</a> ";
}
}
echo "<br>跳轉至第".$pager."頁"; //輸出連結
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.