Cakephp helper to cut the long text without cutting the word

Cakephp helper to cut the long text without cutting the word 29May, 2012

Step 1 : Create a helper file limit_text.php in app.views/helpers/

Note: The same function can be use in other than cakephp

<?php
class LimitTextHelper extends AppHelper{

public function trimText ($text=null,$length=8,$showDots=true,$cutFirstWord=true ) {
$textArr = explode(‘ ‘,$text);
if($showDots){
$dotString = ‘…’;
}else{
$dotString = ”;
}

if($length==0){
echo ucfirst($text);
}else{
if(!$cutFirstWord && strlen($textArr[0])>$length ){
echo ucfirst($textArr[0]).$dotString;
}elseif(strlen($textArr[0])>$length){
echo ucfirst(substr($textArr[0],0,$length)).$dotString;
}else{
if(strlen($text)>$length){
$newText = substr($text,0,$length);
$newText = substr($newText,0,strrpos($newText,” “));
echo ucfirst($newText).$dotString;
}else{
echo ucfirst($text);
}
}
}
}//eof

}
?>

Step 2: Include the helper in the controller

Like:

var $helpers = array(‘Html’,’Javascript’, ‘Ajax’,’Session’,’LimitText’);

Step 3:Now in views

// 3rd param = false if don’t want dots at the end , 4th is set false when a string has one word only and you don’t want to cut the first word

<?php echo $this->LimitText->trimText($text, 40 ); ?>

Example:

$text = “Hello this is the description text to show the format string into the text”;

$this->LimitText->trimText($text, 20 );

Output: Hello this is the…

$text = “Hello this is the description text to show the format string into the text”;

$this->LimitText->trimText($text, 20,false );

Output: Hello this is the

$text = “Hello this is the description text to show the format string into the text”;

$this->LimitText->trimText($text, 4,true,false ); // will not cut the first word if string length is less than or equal 4

Output: Hello…

Posted by: Sumeet Soni / In: Cakephp
Cam