如何用php将文本切碎成一定长度?

如何用php将文本切碎成一定长度?,php,string-concatenation,Php,String Concatenation,我想从数据库中获取一些字段值,并在html中显示它们 但是其中一些比div的宽度长,所以我想在of的时候切掉,如果超过30个字符,在后面加上3个点 windows vs mac os x-> windows vs m... threads about windows vista -> threads about win... 我该怎么做呢?请检查,这应该是您正在寻找的内容。从您的示例判断,您似乎并不关心保留单词,因此,这里是: if (strlen($str) > 30) {

我想从数据库中获取一些字段值,并在html中显示它们

但是其中一些比div的宽度长,所以我想在of的时候切掉,如果超过30个字符,在后面加上3个点

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

我该怎么做呢?

请检查,这应该是您正在寻找的内容。

从您的示例判断,您似乎并不关心保留单词,因此,这里是:

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

如果您需要不止一次执行这种功能,请考虑这个函数:

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;
}

如果使用Smarty,则可以使用修改器

{myLongText|truncate:30:'...':true}
顺便说一句,这样的函数应该存在于任何合适的模板引擎中。

replicate of(sidenote)
chop()
从字符串的末尾去除空白(或其他字符)。对于您的用例来说,更合适的术语是truncate。这三个点实际上被称为省略号,从技术上讲只是一个字符:
..
&hellip作为HTML实体。
{myLongText|truncate:30:'...':true}