在 PHP 中,如何在一定数量的字符后截断文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1241224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:40:28  来源:igfitidea点击:

How do you cut off text after a certain amount of characters in PHP?

phpstringstrip

提问by jiexi

I have two string that i want to limit to lets say the first 25 characters for example. Is there a way to cut off text after the 25th character and add a ... to the end of the string?

我有两个字符串,我想限制为例如前 25 个字符。有没有办法在第 25 个字符之后截断文本并在字符串的末尾添加一个 ...?

So '12345678901234567890abcdefg' would turn into '12345678901234567890abcde...' where 'fg' is cut off.

所以 '12345678901234567890abcdefg' 将变成 '12345678901234567890abcde...',其中 'fg' 被切断。

回答by Tyler Carter

May I make a modification to pallan's code?

我可以修改 pallan 的代码吗?

$truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;

This doesn't add the '...' if it is shorter.

如果它更短,则不会添加“...”。

回答by Pascal MARTIN

To avoid cutting right in the middle of a word, you might want to try the wordwrapfunction ; something like this, I suppose, could do :

为避免在单词中间切入,您可能想尝试使用该wordwrap功能;像这样的事情,我想,可以做:

$str = "this is a long string that should be cut in the middle of the first 'that'";
$wrapped = wordwrap($str, 25);
var_dump($wrapped);

$lines = explode("\n", $wrapped);
var_dump($lines);

$new_str = $lines[0] . '...';
var_dump($new_str);

$wrappedwill contain :

$wrapped将包含:

string 'this is a long string
that should be cut in the
middle of the first
'that'' (length=74)

The $linesarray will be like :

$lines数组将类似于:

array
  0 => string 'this is a long string' (length=21)
  1 => string 'that should be cut in the' (length=25)
  2 => string 'middle of the first' (length=19)
  3 => string ''that'' (length=6)

And, finally, your $new_string:

最后,你的$new_string

string 'this is a long string' (length=21)


With a substr, like this :


使用 substr,像这样:

var_dump(substr($str, 0, 25) . '...');

You'd have gotten :

你会得到:

string 'this is a long string tha...' (length=28)

Which doesn't look that nice :-(

哪个看起来不太好:-(


Still, have fun !


不过,玩得开心!

回答by Peer Allan

Really quickly,

真的很快,

$truncated = substr('12345678901234567890abcdefg', 0, 20) . '...'

回答by Arne

This one is short and takes word boundary into account, it doesn't use loops which makes it very efficient

这个很短,并且考虑了词边界,它不使用循环,这使得它非常有效

function truncate($str, $chars, $end = '...') {
    if (strlen($str) <= $chars) return $str;
    $new = substr($str, 0, $chars + 1);
    return substr($new, 0, strrpos($new, ' ')) . $end;
}

Usage:

用法:

truncate('My string', 5); //returns: My...

回答by eduardogoncalves

http://php.net/manual/en/function.mb-strimwidth.php(PHP 4 >= 4.0.6, PHP 5, PHP 7)

http://php.net/manual/en/function.mb-strimwidth.php (PHP 4 >= 4.0.6, PHP 5, PHP 7)

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
echo "<br />";
echo mb_strimwidth("Hello", 0, 10, "...");
?>

output:

输出:

Hello W...
Hello

回答by MeeDNite

$words=explode(' ', $string);
for($ii = 0,$j=0; $ii< 5 && $j < sizeof($words) ;$j++){
    $ii += strlen($words[$j]);
    $intro= $words[$j]. " ";    
}
$intro.= "...";

I know its to late, but if anyone else is returning to this page, this will do,

我知道为时已晚,但如果其他人返回此页面,则可以这样做,

回答by szsahin

I would go with Pascal MARTIN's answer, with some additional improvements. Because;

我会同意 Pascal MARTIN 的回答,并进行一些额外的改进。因为;

1 - "PHP wordwrap", respects word boundaries automatically

1 - “PHP wordwrap”,自动尊重单词边界

2 - If your string contains a word more than 25 chars(aagh, so there is nothing to do) you can force "PHP wordwrap" to cut word.(improvement)

2 - 如果您的字符串包含超过 25 个字符的单词(aagh,所以没有什么可做的),您可以强制“PHP wordwrap”剪切单词。(改进)

3 - If your string is shorter than 25 chars, then "..." will seem ugly after a complete sentence.(improvement)

3 - 如果你的字符串短于 25 个字符,那么在一个完整的句子之后“...”会看起来很丑。(改进)

$str = "This string might be longer than 25 chars, or might not!";
// we are forcing to cut long words...
$wrapped = wordwrap($str, 25, "\n", 1);
var_dump($wrapped);

$lines = explode("\n", $wrapped);
var_dump($lines);

// if our $str is shorter than 25, there will be no $lines[1]
(array_key_exists('1', $lines)) ? $suffix = '...' : $suffix = '';
$new_str = $lines[0] . $suffix;
var_dump($new_str);

回答by usoban

substrfunction is the right one for you

substr函数适合您

回答by ahawker

You're looking for the substrmethod.

您正在寻找substr方法。

$s = substr($input, 0, 25);

This will get you the first chuck of the string and then you can append whatever you'd like to the end.

这将使您获得字符串的第一个夹头,然后您可以将任何您想要的附加到最后。

回答by Byron Whitlock

 echo substr($str,0,25)."...";

Would do the trick, but if you are dealing with words, you might want to cut off on word boundries so you don't have partial word doig this: The quick bl...

可以解决这个问题,但如果你正在处理单词,你可能想要切断单词边界,这样你就不会有部分单词 doig 这个:快速的 bl...

So to do that (crude off the top of my head):

所以要做到这一点(我的头顶很粗糙):

$words = split(" ", strlen($str));

for($i = 0,$j=0; $i< 25 && $j < sizeof($words) ;$j++)
{
    $i += strlen($words[$j]);
    echo $words[$j]. " ";    
}
echo "...";