archive “2010/11”

slice/paging large contents using php

by Hamid Reza Fahimi Madjd @ Nov 28, 2010

Some days ago i was engaged in wap version of a web based application that had to prepare large content (like articles) for mobile devices.

considering limitation of mobile devices, i decided to slice content to specified bytes (1500 Bytes) and display sliced content instead whole content.

so i wrote a snip code that :

  1. fetch specified bytes
  2. continue to fetching (in both side, left and right) untill get first new line character
define('BYTES_PER_PAGE', 1500);
define('PAGE_NO', ((int)@$_GET['page']) == 0? 1: (int)@$_GET['page']);
$len = mb_strlen($description, 'utf-8');

if($len > BYTES_PER_PAGE) {
  $len = ($len%BYTES_PER_PAGE == 0? (int)$len/BYTES_PER_PAGE: (int)($len/BYTES_PER_PAGE)+1 ) ;
  $start = (PAGE_NO - 1) * BYTES_PER_PAGE;
  $end = PAGE_NO * BYTES_PER_PAGE;

  // go back till get first new line char
  while($start > 0 && ord(mb_substr($description, --$start, 1, 'utf-8')) != 10);

  // go forward till get first new line char
  while($end < mb_strlen($description, 'utf-8') && ord(mb_substr($description, $end++, 1, 'utf-8')) != 10);
  $description = mb_substr($description, $start, $end-$start, 'utf-8');
}

as you see, because of utf8 string, i used  mb_* functions, you can replace it with normal string functions.

php comments no comment

last tweet