我是烏鳥heart,文章來源:http://www.cnblogs.com/wuniaoheart
相關地址:http://wuniaoheart.iteye.com
歡迎交流!實現代碼如下:
1 <?php include('include/config.php'); ?> 2 <?php 3 /** 4 *Author:烏鳥heart 5 *實現長文章分頁的代碼 6 *原理: 7 *利用一個數組來記錄文章每一頁(用p0、p1、p2...做手動標記)的起始字節數,然后通過利用php函數操作這個數組去顯示分頁后的文章。分頁顯示,傳遞ptag(與tag的值一樣)值。 8 *利用到的php函數: 9 *1、strlen("字符串") - Returns the length of the given string. - 返回字符串的字節總數。 10 *2、strpos("字符串","匹配字符") - Returns the numeric position of the first occurrence of needle in the haystack string. - 返回字符串中出現的第一個相匹配的字符所在的字節序數。 11 *3、substr("字符串","起始位置","終止位置") - substr() returns the portion of string specified by the start and length parameters. - 返回字符串中指定起止位置的若干字符。 12 */ 13 $sql = "select * from article where id = 41";//定義sql語句,返回id為41的內容 14 $result = mysql_query($sql);//執行sql語句,返回結果集 15 $row = mysql_fetch_array($result);//以數組的形式從記錄集返回 16 $content = $row['content'];//把文章賦給變量$content 17 $articleCounts = strlen($content);//返回$content(文章)的總字節數 18 $isTrue = true;//循環標記 19 $tag = 0;//分頁標記、數組下標 20 echo "字節總數:".$articleCounts."<br>";//測試信息 21 22 23 //尋找標記“ptag”,並把其位置(所在的字節數)賦給數組array[]------------------------------------------ 24 while($isTrue){ 25 $startAt = strpos($content,"p".$tag);//得到相應ptag的字節序數 26 if($startAt != false){ //如果有標記(返回值不是false),則記錄位置 27 $array[$tag++] = $startAt; 28 }else{ //如果沒有標記,則將數組array[0]賦值'\0' 29 $array[$tag] = '\0'; 30 $isTrue = false; 31 } 32 } 33 34 35 //循環輸出標記位置-------------------------------------------------------------測試信息 36 for($i = 0; $i < $tag; $i++){ 37 echo $array[$i]."<br>"; 38 } 39 echo "------------------------------ <br>"; 40 41 42 //輸出內容--------------------------------------------------------------------- 43 if($array[0] == '\0'){ //判斷是否有標記 44 echo $content; //沒有標記的情況,單頁顯示 45 }else{ //有標記的情況,分頁顯示 46 //輸出分頁內容 47 if( isset($_GET['ptag']) ){ //判斷是否有ptag值傳遞,有則顯示第 ptag+1 頁,否則顯示第一頁(ptag=0) 48 $ptag = $_GET['ptag']; //把ptag的值賦給變量$ptag 49 if($ptag < $tag){ //判斷參數是否有誤 50 echo "有值傳遞,顯示第".($ptag+1)."頁<br>"; //測試信息 51 echo "值為:".$ptag."<br>"; //測試信息 52 echo substr($content,$array[$ptag - 1] + 2,$array[$ptag] - $array[$ptag - 1] - 2);//顯示ptag+1頁的內容 53 }else{echo "參數有誤";} 54 } 55 else{ //沒有ptag值傳遞的情況,顯示第一頁(ptag=0) 56 echo "無值傳遞,顯示第1頁<br>"; //測試信息 57 echo substr($content,0,$array[0] - 1);//顯示第一頁的內容 58 } 59 } 60 61 62 //循環顯示頁數鏈接------------------------------------------------------------- 63 if($array[0] != '\0'){ //在有手動標記的情況下才顯示頁數鏈接 64 for($i = 0;$i < $tag;$i++){ 65 if($ptag == $i){ //如果是本頁,則粗體顯示 66 $pager .= " <a href='test.php?ptag=$i'><b>".($i+1)."</b></a> "; 67 }else{ //不是本頁 68 $pager .= " <a href='test.php?ptag=$i'>".($i+1)."</a> "; 69 } 70 } 71 echo "<br>跳轉至第".$pager."頁"; //輸出鏈接 72 } 73 74 ?>
OK,DONE!