如何在PHP中获得字符串的前n个字符?什么是最快的方法来修剪一个字符串到特定的字符数,并添加'…如果需要的话?


当前回答

如果对截断字符串的长度没有硬性要求,可以使用这个来截断并防止截断最后一个单词:

$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";

// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);

// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));

// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));

在本例中,$preview将是“Knowledge is a natural right of every human”。

动态代码示例: http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713

其他回答

使用子串

http://php.net/manual/en/function.substr.php

$foo = substr("abcde",0, 3) . "...";

我使用的函数是:

function cutAfter($string, $len = 30, $append = '...') {
        return (strlen($string) > $len) ? 
          substr($string, 0, $len - strlen($append)) . $append : 
          $string;
}

看到它的行动。

如果你想要切割,小心不要分割单词,你可以做下面的事情

function ellipse($str,$n_chars,$crop_str=' [...]')
{
    $buff=strip_tags($str);
    if(strlen($buff) > $n_chars)
    {
        $cut_index=strpos($buff,' ',$n_chars);
        $buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
    }
    return $buff;
}

如果$str比$n_chars短,则原形返回。

如果$str等于$n_chars也会返回它。

如果$str比$n_chars长,那么它会寻找下一个空格来切割,或者(如果直到最后没有更多的空格)$str会在$n_chars被粗鲁地切割。

注意:注意此方法将删除HTML中的所有标记。

if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";

我不确定这是否是最快的解决方案,但它看起来是最短的:

$result = current(explode("\n", wordwrap($str, $width, "...\n")));

附注:见一些例子在这里https://stackoverflow.com/a/17852480/131337