php 将文本修剪为 340 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2104653/
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
Trim text to 340 chars
提问by CLiown
I'm pulling blog posts from a DB. I want to trim the text to a max length of 340 characters.
我正在从数据库中提取博客文章。我想将文本修剪为 340 个字符的最大长度。
If the blog post is over 340 characters I want to trim the text to the last full word and add '...' on the end.
如果博客文章超过 340 个字符,我想将文本修剪到最后一个完整单词并在末尾添加“...”。
E.g.
NOT: In the begin....
BUT: In the ...
回答by Nicholas Flynt
It seems like you would want to first trim the text down to 340 characters exactly, then find the location of the last ' ' in the string and trim down to that amount. Like this:
似乎您希望首先将文本精确地修剪为 340 个字符,然后找到字符串中最后一个 ' ' 的位置并将其修剪为该数量。像这样:
$string = substr($string, 0, 340);
$string = substr($string, 0, strrpos($string, ' ')) . " ...";
回答by onokazu
If you have the mbstring extension enabled (which is on most servers nowadays), you can use the mb_strimwidth function.
如果您启用了 mbstring 扩展(现在在大多数服务器上),您可以使用 mb_strimwidth 函数。
echo mb_strimwidth($string, 0, 340, '...');
回答by Mark Byers
The other answers show you how you can make the text roughly340 characters. If that's fine for you, then use one of the other answers.
其他答案向您展示了如何使文本大约为340 个字符。如果这对您来说没问题,请使用其他答案之一。
But if you want a very strict maximumof 340 characters, the other answers won't work. You need to remember that adding the '...'can increase the length of the string and you need to take account of that.
但是,如果您想要非常严格的最多340 个字符,则其他答案将不起作用。您需要记住,添加'...'可以增加字符串的长度,您需要考虑到这一点。
$max_length = 340;
if (strlen($s) > $max_length)
{
$offset = ($max_length - 3) - strlen($s);
$s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}
Note also that here I'm using the overload of strrposthat takes an offset to start searching directly from the correct location in the string, rather than first shortening the string.
另请注意,这里我使用的重载strrpos需要一个偏移量来直接从字符串中的正确位置开始搜索,而不是首先缩短字符串。
See it working online: ideone
在线查看:ideone
回答by John Conde
try:
尝试:
preg_match('/^.{0,340}(?:.*?)\b/siu', $text, $matches);
echo $matches[0] . '...';
回答by Sebastian Hojas
I put the answer of John Conde in a method:
我把约翰康德的答案放在一个方法中:
function softTrim($text, $count, $wrapText='...'){
if(strlen($text)>$count){
preg_match('/^.{0,' . $count . '}(?:.*?)\b/siu', $text, $matches);
$text = $matches[0];
}else{
$wrapText = '';
}
return $text . $wrapText;
}
Examples:
例子:
echo softTrim("Lorem Ipsum is simply dummy text", 10);
/* Output: Lorem Ipsum... */
echo softTrim("Lorem Ipsum is simply dummy text", 33);
/* Output: Lorem Ipsum is simply dummy text */
echo softTrim("LoremIpsumissimplydummytext", 10);
/* Output: LoremIpsumissimplydummytext... */
回答by D. Cichowski
Why this way?
为什么这样?
- I like the regexsolution over substring, to catch any other than whitespace word breaks (interpunction etc.)
- John Condoe's solution is not perfectly correct, since it trim text to 340 characters and thenfinish the last word (so will often be longer than desired)
- 我喜欢substring 上的正则表达式解决方案,以捕捉除空格以外的任何断词(间断等)
- John Condoe 的解决方案并不完全正确,因为它将文本修剪为 340 个字符,然后完成最后一个单词(因此通常会比预期的要长)
Actual regexsolution is very simple:
实际的正则表达式解决方案非常简单:
/^(.{0,339}\w\b)/su
Full method in PHP could look like this:
PHP 中的完整方法可能如下所示:
function trim_length($text, $maxLength, $trimIndicator = '...')
{
if(strlen($text) > $maxLength) {
$shownLength = $maxLength - strlen($trimIndicator);
if ($shownLength < 1) {
throw new \InvalidArgumentException('Second argument for ' . __METHOD__ . '() is too small.');
}
preg_match('/^(.{0,' . ($shownLength - 1) . '}\w\b)/su', $text, $matches);
return (isset($matches[1]) ? $matches[1] : substr($text, 0, $shownLength)) . $trimIndicator ;
}
return $text;
}
More explanation:
更多解释:
$shownLengthis to keep very strict limit (like Mark Byers mentioned)- Exception is thrown in case given length was too small
\w\bpart is to avoid whitespace or interpunction at the end (see 1 below)- In case first word would be longer than desired max length, that word will be brutally cut
$shownLength是保持非常严格的限制(如 Mark Byers 提到的)- 如果给定的长度太小,则会抛出异常
\w\b部分是避免在末尾出现空格或打断(见下文 1)- 如果第一个单词比所需的最大长度长,该单词将被残酷地剪掉
- Despite the fact that in question result
In the ...is described as desired, I feelIn the...is more smooth (also don't likeIn the,...etc.)
- 尽管有问题的结果
In the ...被描述为想要的,但我觉得In the...更流畅(也不喜欢In the,...等)
回答by rahul sharma
Simplest solution
最简单的解决方案
$text_to_be_trim= "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard.";
if(strlen($text_to_be_trim) > 20)
$text_to_be_trim= substr($text_to_be_trim,0,20).'....';
For multi-byte text
对于多字节文本
$stringText= "UTIL CONTROL DISTRIBUCION AMARRE CIGüE?AL";
$string_encoding = 'utf8';
$s_trunc = mb_substr($stringText, 0, 37, $string_encoding);
echo $s_trunc;
回答by ghostdog74
you can try using functions that comes with PHP , such as wordwrap
你可以尝试使用 PHP 自带的函数,比如 wordwrap
print wordwrap($text,340) . "...";
回答by sjkon
function trim_characters( $text, $length = 340 ) {
函数trim_characters($text,$length = 340){
$length = (int) $length;
$text = trim( strip_tags( $text ) );
if ( strlen( $text ) > $length ) {
$text = substr( $text, 0, $length + 1 );
$words = preg_split( "/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY );
preg_match( "/[\s]| /", $text, $lastchar, 0, $length );
if ( empty( $lastchar ) )
array_pop( $words );
$text = implode( ' ', $words );
}
return $text;
}
}
Use this function trim_characters() to trims a string of words to a specified number of characters, gracefully stopping at white spaces. I think this is helpful to you.
使用此函数 trim_characters() 将一串单词修剪为指定数量的字符,优雅地停在空格处。我认为这对你有帮助。

