There are certain situations when we need to truncate a text.. for example if we want to show only some parts of a text.. like what we see in google search.. a small description is shown..
to face such situations i have kept a function and named it as truncate.. and have included the code in my helper file.. so that i have access to this function from anywhere within the project..
the code is
<?php
/*
$string: is the text to truncate
$start : is the starting count of the text from which the text is to be truncated.. normaly it will be zero. taht is text is from the begining
$length : refers to the count of characters to return back. the function takes it as a apporximate value. because function searches for the nearby 'space' in the $roundof characters limit
so $roundof : is the count of characters for the near by space,,..
$append is the characters to be appended after the truncated string for example : " like this..." (three dots)
*/
function truncate($string, $start = 0,$length = 250 ,$append="...",$roundof=5){
if (strlen($string) < $length){
return $string;
}else{
$around=$length-$roundof;
$whitespaceposition = strpos($string," ",$around);
$truncated = substr($string, 0, $whitespaceposition);
$truncated.=$append;
return $truncated;
}
return TRUE;
}
// example
$text ="hai how are you friend";
// want to truncate the text in 5characters
print truncate($text,0,5);
/*
output
hai h...
*/
?>
--
Thanks & regards
Saxan Rappai.
moderator: http://makemytaste.com
Friday, May 28, 2010
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment