How to slice text of a certain length using php?

I want to get some field values ​​from a database and present them in html.

but some of them are longer than the width of the div, so I wanted to cut the if and add 3 dots after them if they are longer than 30 characters allow.

windows vs mac os x-> windows vs m...
threads about windows vista -> threads about win...

How can i do this?

+3
source share
4 answers

If you need to perform such functions more than once, consider this function:

function truncate($string, $limit, $break = '.', $pad = '...')
{
    // return with no change if string is shorter than $limit
    if(strlen($string) <= $limit) return $string;

    // is $break present between $limit and the end of the string?
    if(false !== ($breakpoint = strpos($string, $break, $limit)))
    {
        if($breakpoint < strlen($string) - 1)
        {
            $string = substr($string, 0, $breakpoint) . $pad;
        }
    }

    return $string;
}

Using:

echo truncate($string, 30);
+6
source

Judging by your examples, you don't seem to care about keeping words, so here it is:

if (strlen($str) > 30)
{
    echo substr($str, 0, 30) . '...';
}
+1
source

Smarty, .

{myLongText|truncate:30:'...':true}

, .

0
-2
source

Source: https://habr.com/ru/post/1730646/


All Articles