EllisLab text mark
Advanced Search
     
text_helper:character_limiter
Posted: 27 July 2007 06:02 AM
Joined: 2007-07-14
26 posts

Ok, not exactly a bug (its documented) but slightly silly behavior if you ask me:

The character_limiter helper normally returns a string larger than the max length specified. This is silly, what if I want to store the text in a limited length VARCHAR field? You could still have some truncation occurring!

Better:

function character_limiter($str$n 500$end_char '…')
{
    
if (strlen($str) < $n)
    
{
        
return $str;
    
}
        
    $str 
preg_replace("/\s+/"' 'preg_replace("/(\r\n|\r|\n)/"" "$str));

    if (
strlen($str) <= $n)
    
{
        
return $str;
    
}
                                    
    $out 
"";
    
$n--; //for end_char
    
foreach (explode(' 'trim($str)) as $val)
    
{

        
if (strlen($out.$val.' ') >= $n)
        
{
            
return trim($out).$end_char;
        
}        
        $out 
.= $val.' ';            
    
}
 
Posted: 28 July 2007 08:59 PM   [ # 1 ]   [ Rating: 0 ]
Avatar
Joined: 2007-07-28
1 posts
Al James - 27 July 2007 10:02 AM
$n--; //for end_char 

It’s not a solution because You must know size of $end_char, i.e. standard $end_char has 7 char so You must put this

$n -= 7


I have found bug too. When last word in string was between string length and limiter, function return string(without changes) and end character, i.e.

character_limiter('Hello world'10); 
return:

Hello world…

My solution(maybe it help You Al James):

function character_limiter($str$n 500$end_char '&#8230;')
{
    $len 
strlen($str);//length of original string
    
    
if (strlen($str) < $n)
    
{
        
return $str;
    
}
        
    $str 
preg_replace("/\s+/"' 'preg_replace("/(\r\n|\r|\n)/"" "$str));

    if (
strlen($str) <= $n)
    
{
        
return $str;
    
}
                                    
    $out 
"";
    foreach (
explode(' 'trim($str)) as $val)
    
{
        $out 
.= $val.' ';
        if (
strlen(trim($out)) == $len// if length not change return original string
        

            
return trim($out);
        
}
        
elseif (strlen($out) >= $n)
        
{
            
return trim($out).$end_char;
        
}        
    }

Sorry for my bad english smirk