开发者

how to chop of a text in a certain length with php?

i wanna get some field values from database and present them on html.

but some of them are longer than the div width so i wanted to chop if of and add 3 dots after them if they are longer than lets say 30 characthers.

windows vs mac os x-> windows vs m...
threads about windows vista -> threads about win...
开发者_JS百科

how can i do that?


If you need to perform this kind of functionality 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;
}

Usage:

echo truncate($string, 30);


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

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


If you use Smarty, you can use the truncate modifier.

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

BTW, such kind of function should exist in any decent template engine.


Check out wordwrap(), that should be what you're looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜