Function to summarize string in php [duplicate]

1

Well I have the following function to summarize a string in php.

function resumo($string,$chars) {
if (strlen($string) > $chars) {
    while (substr($string, $chars, 1) <> ' ' && ($chars < strlen($string))) {
        $chars++;
    }
}
return substr($string, 0, $chars);
}

echo resumo("bla bla bla bla bla", 4);

Well the problem I'm having is the following. I would like to know the number of letters at most, and the function is returning more letters.

And whenever the sting is summed up I want to add (...) three points. If I enter a string that does not need to be summarized, it is not necessary to add all three points.

    
asked by anonymous 26.07.2017 / 16:29

2 answers

3
function resumo($string, $chars) {
    if (strlen($string) > $chars)
        return substr($string, 0, $chars).'...';
    else
        return $string;
}

echo resumo("abcde", 4);

Output

  

abcd ...

You can also use the mb_strimwidth function, you can use it this way :

function resumo($string, $chars) {
    return mb_strimwidth($string, 0, $chars + 3, "...");
}

As the answer from @Wallace

    
26.07.2017 / 16:36
2

You can simplify your function with only substr() or mb_substr() as a return and change the function signature to add ... if no argument is passed:

function resumo($string, $chars=0) {
    if(!mb_strlen($string)) return '';
    return  $chars == 0 ? $string : substr($string, 0, $chars)  .'...';
}

echo resumo("bla bla bla bla bla", 4); //Output = "bla ..."
echo resumo("bla bla bla bla bla");    //Output = "bla bla bla bla bla"
echo resumo("bl", 5);                  //Output = "bl..."

See working at repl.it .

    
26.07.2017 / 16:38