Welcome Guest, Not a member yet? Register   Sign In
text_helper:character_limiter
#1

[eluser]Al James[/eluser]
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:

Code:
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.' ';            
    }
}
#2

[eluser]Unknown[/eluser]
[quote author="Al James" date="1185544930"]
Code:
$n--; //for end_char
[/quote]
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
Code:
$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.
Code:
character_limiter('Hello world', 10);
return:
Quote:Hello world…

My solution(maybe it help You Al James):
Code:
function character_limiter($str, $n = 500, $end_char = '…')
{
    $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 Confusedmirk:




Theme © iAndrew 2016 - Forum software by © MyBB