如何从字符串中获取第一个x字符,而不切断最后一个字?

Pra*_*ant 13 php string substr

我在变量中有以下字符串.

Stack Overflow is as frictionless and painless to use as we could make it.

我想从上面的行中获取前28个字符,所以通常如果我使用substr然后它会给我Stack Overflow is as frictio这个输出,但我想输出为:

Stack Overflow is as...

PHP中是否有任何预制函数可以这样做,或者请在PHP中为我提供此代码?

编辑:

我想要从字符串中总共28个字符而不会破坏一个单词,如果它会让我少于28个字符而不会破坏一个单词,那很好.

Gre*_*reg 51

您可以使用该wordwrap()功能,然后在换行符上爆炸并采取第一部分:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
Run Code Online (Sandbox Code Playgroud)


Joh*_*ica 10

来自AlfaSky:

function addEllipsis($string, $length, $end='…')
{
    if (strlen($string) > $length)
    {
        $length -= strlen($end);
        $string  = substr($string, 0, $length);
        $string .= $end;
    }

    return $string;
}
Run Code Online (Sandbox Code Playgroud)

Elliott Brueggeman博客的另一个更具特色的实现:

/**
 * trims text to a space then adds ellipses if desired
 * @param string $input text to trim
 * @param int $length in characters to trim to
 * @param bool $ellipses if ellipses (...) are to be added
 * @param bool $strip_html if html tags are to be stripped
 * @return string 
 */
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
    //strip tags, if desired
    if ($strip_html) {
        $input = strip_tags($input);
    }

    //no need to trim, already shorter than trim length
    if (strlen($input) <= $length) {
        return $input;
    }

    //find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    $trimmed_text = substr($input, 0, $last_space);

    //add ellipses (...)
    if ($ellipses) {
        $trimmed_text .= '...';
    }

    return $trimmed_text;
}
Run Code Online (Sandbox Code Playgroud)

(谷歌搜索:"php trim ellipses")