14

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

Stack Overflow 使用起来尽可能顺畅无痛。

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

堆栈溢出就像...

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

编辑:

我想要字符串中的总共 28 个字符而不破坏一个单词,如果它返回的字符少于 28 个而不破坏一个单词,那很好。

4

13 回答 13

53

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

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
于 2009-07-09T14:42:25.137 回答
11

来自阿尔法天空

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

    return $string;
}

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

(谷歌搜索:“php 修剪椭圆”)

于 2009-07-09T14:42:16.497 回答
3

这是您可以做到的一种方法:

$str = "Stack Overflow is as frictionless and painless to use as we could make it.";

$strMax = 28;
$strTrim = ((strlen($str) < $strMax-3) ? $str : substr($str, 0, $strMax-3)."...");

//or this way to trim to full words
$strFull = ((strlen($str) < $strMax-3) ? $str : strrpos(substr($str, 0, $strMax-3),' ')."...");
于 2009-07-09T14:42:19.273 回答
3

这是最简单的方法:

<?php 
$title = "this is the title of my website!";
$number_of_characters = 15;
echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " "));
?>
于 2012-05-08T20:14:05.647 回答
2

这是我所知道的最简单的解决方案...

substr($string,0,strrpos(substr($string,0,28),' ')).'...';
于 2009-07-09T14:45:52.727 回答
0

尝试:

$string='Stack Overflow is as frictionless and painless to use as we could make it.';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');

$string='Stack Overflow';
$n=28;
$break=strpos(wordwrap($string, $n,'<<||>>'),'<<||>>');
print substr($string,0,($break==0?strlen($string):$break)).(strlen($string)>$n?'...':'');
于 2009-07-09T14:42:04.873 回答
0

我会使用字符串标记器将字符串拆分为类似这样的单词:

$string = "Stack Overflow is as frictionless and painless to use as we could make it.";
$tokenized_string = strtok($string, " ");

然后,您可以以任何您想要的方式提取单个单词。


编辑:格雷格有一种更好、更优雅的方式来做你想做的事。我会选择他的 wordwrap() 解决方案。

于 2009-07-09T14:45:01.840 回答
0

你可以使用wordwrap

string wordwrap  ( string $str  [, int $width= 75  [, string $break= "\n"  [, bool $cut= false  ]]] )

-

function firstNChars($str, $n) {
  return array_shift(explode("\n", wordwrap($str, $n)));
}

echo firstNChars("bla blah long string", 25) . "...";

免责声明:没有测试它。

此外,如果您的字符串包含\ns,它可能会更早损坏。

于 2009-07-09T14:48:27.373 回答
0
function truncate( $string, $limit, $break=" ", $pad="...") {

 // return with no change if string is shorter than $limit
 if(strlen($string) <= $limit){
    return $string;
 }

 $string = substr($string, 0, $limit);
 if(false !== ($breakpoint = strrpos($string, $break))){
    $string = substr($string, 0, $breakpoint);
 }
 return $string . $pad;
}
于 2010-06-22T17:18:34.623 回答
0

如果您的字符串包含 html 标记、  和多个空格,则可能会出现问题。这是我用来处理一切的东西:

function LimitText($string,$limit,$remove_html=0){
    if ($remove_html==1){$string=strip_tags($string);}
    $newstring = preg_replace("/(?:\s|&nbsp;)+/"," ",$string, -1); // replace &nbsp with space
    $newstring = preg_replace(array('/\s{2,}/','/[\t\n]/'),' ',$newstring); // replace duplicate spaces
    if (strlen($newstring)<=$limit) { return $newstring; } // ensure length is more than $limit
    $newstring = substr($newstring,0,strrpos(substr($newstring,0,$limit),' '));
    return $newstring;
}

用法:

$string = 'My wife is jealous of stackoverflow';
echo LimitText($string,20);
// My wife is jealous

与 html 一起使用:

$string = '<div><p>My wife is jealous of stackoverflow</p></div>';
echo LimitText($string,20,1);
// My wife is jealous
于 2015-10-29T11:27:47.437 回答
0

这对我有用

function WordLimt($Keyword,$WordLimit){

    if (strlen($Keyword)<=$WordLimit) { return $Keyword; }
    $Keyword= substr($Keyword,0,strrpos(substr($Keyword,0,$WordLimit),' '));
    return $Keyword;
}

echo WordLimt($MyWords,28);

// OutPut : Stack Overflow is as

它会在最后一个空格上调整和中断,而不用删减词...

于 2016-08-11T14:23:35.323 回答
-1

为什么不尝试分解它并获取数组的前 4 个元素呢?

于 2009-07-09T14:41:54.890 回答
-1
substr("some string", 0, x);

来自PHP 手册

于 2009-07-09T14:42:23.953 回答