如何从字符串中获取第一个x字符,而不会删除最后一个字?

时间:2021-12-30 21:35:25

I have the following string in a variable.

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

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

I want to fetch first 28 characters from the above line, so normally if I use substr then it will give me Stack Overflow is as frictio this output but I want output as:

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

Stack Overflow is as...

Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP?

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

Edited:

I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.

我想要从字符串中总共28个字符而不会破坏一个单词,如果它会使我少几个字符而不是一个字而不会破坏一个单词,这很好。

13 个解决方案

#1


50  

You can use the wordwrap() function, then explode on newline and take the first part:

你可以使用wordwrap()函数,然后在换行符上爆炸并采取第一部分:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';

#2


10  

From AlfaSky:

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

    return $string;
}

An alternate, more featureful implementation from Elliott Brueggeman's blog:

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

(Google search: "php trim ellipses")

(谷歌搜索:“php trim ellipses”)

#3


3  

Here's one way you could do it:

这是你可以做到的一种方式:

$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),' ')."...");

#4


2  

This is the simplest solution I know of...

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

substr($string,0,strrpos(substr($string,0,28),' ')).'...';

#5


2  

This is the easiest way:

这是最简单的方法:

<?php 
$title = "this is the title of my website!";
$number_of_characters = 15;
echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " "));
?>

#6


0  

I would use a string tokenizer to split the string into words much like this:

我会使用字符串标记生成器将字符串拆分为单词,如下所示:

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

Then you can pull out the individual words any way you want.

然后你可以按照你想要的方式提取单个单词。


Edit: Greg has a much better and more elegant way of doing what you want. I would go with his wordwrap() solution.

编辑:格雷格有一个更好,更优雅的方式做你想要的。我会用他的wordwrap()解决方案。

#7


0  

you can use wordwrap.

你可以使用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) . "...";

disclaimer: didn't test it.

免责声明:没有测试。

additionally, if your string contains \ns, it might get broken earlier.

另外,如果你的字符串包含\ ns,它可能会更早被破坏。

#8


0  

try:

$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?'...':'');

#9


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

#10


0  

Problems can arise if your string has html tags, &nbsp and multiple spaces. Here is what I use that takes care of everything:

如果您的字符串包含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;
}

usage:

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

usage with html:

使用html:

$string = '<div><p>My wife is jealous of *</p></div>';
echo LimitText($string,20,1);
// My wife is jealous

#11


0  

This's Working for me Perfect

这对我来说很完美

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

it will adjust and break on last Space without cut word...

它将在最后一个空间上进行调整和打破而不会被切断...

#12


-1  

why not try exploding it and getting the first 4 elements of the array?

为什么不尝试爆炸它并获得数组的前4个元素?

#13


-1  

substr("some string", 0, x);

From the PHP Manual

从PHP手册

#1


50  

You can use the wordwrap() function, then explode on newline and take the first part:

你可以使用wordwrap()函数,然后在换行符上爆炸并采取第一部分:

$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';

#2


10  

From AlfaSky:

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

    return $string;
}

An alternate, more featureful implementation from Elliott Brueggeman's blog:

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

(Google search: "php trim ellipses")

(谷歌搜索:“php trim ellipses”)

#3


3  

Here's one way you could do it:

这是你可以做到的一种方式:

$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),' ')."...");

#4


2  

This is the simplest solution I know of...

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

substr($string,0,strrpos(substr($string,0,28),' ')).'...';

#5


2  

This is the easiest way:

这是最简单的方法:

<?php 
$title = "this is the title of my website!";
$number_of_characters = 15;
echo substr($title, 0, strrpos(substr($title, 0, $number_of_characters), " "));
?>

#6


0  

I would use a string tokenizer to split the string into words much like this:

我会使用字符串标记生成器将字符串拆分为单词,如下所示:

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

Then you can pull out the individual words any way you want.

然后你可以按照你想要的方式提取单个单词。


Edit: Greg has a much better and more elegant way of doing what you want. I would go with his wordwrap() solution.

编辑:格雷格有一个更好,更优雅的方式做你想要的。我会用他的wordwrap()解决方案。

#7


0  

you can use wordwrap.

你可以使用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) . "...";

disclaimer: didn't test it.

免责声明:没有测试。

additionally, if your string contains \ns, it might get broken earlier.

另外,如果你的字符串包含\ ns,它可能会更早被破坏。

#8


0  

try:

$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?'...':'');

#9


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

#10


0  

Problems can arise if your string has html tags, &nbsp and multiple spaces. Here is what I use that takes care of everything:

如果您的字符串包含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;
}

usage:

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

usage with html:

使用html:

$string = '<div><p>My wife is jealous of *</p></div>';
echo LimitText($string,20,1);
// My wife is jealous

#11


0  

This's Working for me Perfect

这对我来说很完美

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

it will adjust and break on last Space without cut word...

它将在最后一个空间上进行调整和打破而不会被切断...

#12


-1  

why not try exploding it and getting the first 4 elements of the array?

为什么不尝试爆炸它并获得数组的前4个元素?

#13


-1  

substr("some string", 0, x);

From the PHP Manual

从PHP手册