I have asked a similar question here before, but I need to know if this little tweak is possible. I want to shorten a string to 100 characters and use $small = substr($big, 0, 100);
to do so. However, this just takes the first 100 characters and doesn't care whether it breaks up a word or not.
我之前也问过类似的问题,但我需要知道这个小调整是否可行。我想将字符串缩短为100个字符,并使用$small = substr($big, 0,100);这样做。但是,这只需要前100个字符,而不管它是否拆分一个单词。
Is there any way to take up to the first 100 characters of a string but make sure you don't break a word?
有什么方法可以让一个字符串的前100个字符都不出错呢?
Example:
例子:
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"
$small = some_function($big);
$small = "This is a sentence that has more than 100 characters in it, and I want to return a string of only"
Is there a way to do this using PHP?
有没有一种方法可以使用PHP来实现这一点?
18 个解决方案
#1
114
All you need to do is use:
你所需要做的就是:
$pos=strpos($content, ' ', 200);
substr($content,0,$pos );
#2
31
Yes, there is. This is a function I borrowed from a user on a different forums a a few years back, so I can't take credit for it.
是的,有。这是几年前我从另一个论坛上的用户那里借来的一个功能,所以我不能把它当成自己的功劳。
//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
$length = abs((int)$length);
if(strlen($text) > $length) {
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}
Note that it automatically adds ellipses, if you don't want that just use '\\1'
as the second parameter for the preg_replace
call.
注意,如果您不希望使用“\1”作为preg_replace调用的第二个参数,它会自动添加省略号。
#3
20
If you define words as "sequences of characters delimited by space"... Use strrpos()
to find the last space in the string, shorten to that position, trim the result.
如果你将单词定义为“由空间分隔的字符序列”……使用strrpos()查找字符串中的最后一个空格,缩短到该位置,调整结果。
#4
13
Sure. The easiest is probably to write a wrapper around preg_match:
确定。最简单的方法可能是围绕preg_match编写一个包装:
function limitString($string, $limit = 100) {
// Return early if the string is already shorter than the limit
if(strlen($string) < $limit) {return $string;}
$regex = "/(.{1,$limit})\b/";
preg_match($regex, $string, $matches);
return $matches[1];
}
EDIT : Updated to not ALWAYS include a space as the last character in the string
编辑:更新为不总是包含空格作为字符串中的最后一个字符
#5
10
This function shortens a string by adding "..."
at a word boundary whenever possible. The returned string will have a maximum length of $len
including "..."
.
这个函数通过在一个单词边界添加“…”来缩短一个字符串。返回的字符串的最大长度为$len,包括“…”。
function truncate($str, $len) {
$tail = max(0, $len-10);
$trunk = substr($str, 0, $tail);
$trunk .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len-$tail))));
return $trunk;
}
Examples outputs:
例子的输出:
-
truncate("Thanks for contributing an answer to Stack Overflow!", 15)
returns"Thanks for..."
- 截断(“感谢您为Stack Overflow提供一个答案!”)“谢谢你……”
-
truncate("To learn more, see our tips on writing great answers.", 15)
returns"To learn more..."
(comma also truncated) - 截短(“要了解更多,请参阅我们写好答案的技巧。”“为了学到更多……”(逗号也截断)
-
truncate("Pseudopseudohypoparathyroidism", 15)
returns"Pseudopseudo..."
- 截断(“Pseudopseudohypoparathyroidism”,15)返回“Pseudopseudo……”
#6
6
This is my approach, based on amir's answer, but it doesn't let any word make the string longer than the limit, by using strrpos() with a negative offset.
这是我的方法,基于amir的答案,但是它不允许任何单词使字符串超过限制,使用带有负偏移量的strrpos()。
Simple but works. I'm using the same syntax as in Laravel's str_limit() helper function, in case you want to use it on a non-Laravel project.
简单而有效。我使用的语法与Laravel的str_limit() helper函数相同,以防您想在非Laravel项目上使用它。
function str_limit($value, $limit = 100, $end = '...')
{
$limit = $limit - mb_strlen($end); // Take into account $end string into the limit
$valuelen = mb_strlen($value);
return $limit < $valuelen ? mb_substr($value, 0, mb_strrpos($value, ' ', $limit - $valuelen)) . $end : $value;
}
#7
4
This works fine for me, I use it in my script
这对我来说很好,我在脚本中使用它
<?PHP
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!";
$small = some_function($big);
echo $small;
function some_function($string){
$string = substr($string,0,100);
$string = substr($string,0,strrpos($string," "));
return $string;
}
?>
good luck
祝你好运
#8
4
Here is great solution with dotts at the end with full words
这里有一个伟大的解决方案与dotts结尾的全文
function text_cut($text, $length = 200, $dots = true) {
$text = trim(preg_replace('#[\s\n\r\t]{2,}#', ' ', $text));
$text_temp = $text;
while (substr($text, $length, 1) != " ") { $length++; if ($length > strlen($text)) { break; } }
$text = substr($text, 0, $length);
return $text . ( ( $dots == true && $text != '' && strlen($text_temp) > $length ) ? '...' : '');
}
Input: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
输入:Lorem ipsum ipsum dolor sit amet, committed adipisicing elit, sed do eiusmod tempincior didunt ut le and dolore magna aliqua。但是,如果你的工作是你的工作,那么你的工作就会变得很好。这是一份来自欧盟的报告。但是,在没有任何证据的情况下,我们可以用它来证明我的工作。
Output: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip...
输出:Lorem ipsum ipsum dolor sit amet, committed adipisicing elit, sed do eiusmod tempincior didunt ut le and dolore magna aliqua。如果您有更好的听力原文,欢迎提供给大耳朵,如果被采用,您将获得20到100金币的奖励!
#9
2
This did it for me...
这是为了我……
//trim message to 100 characters, regardless of where it cuts off
$msgTrimmed = mb_substr($var,0,100);
//find the index of the last space in the trimmed message
$lastSpace = strrpos($msgTrimmed, ' ', 0);
//now trim the message at the last space so we don't cut it off in the middle of a word
echo mb_substr($msgTrimmed,0,$lastSpace)
#10
2
Here's my solution:
这是我的解决方案:
/**
* get_words_until() Returns a string of delimited text parts up to a certain length
* If the "words" are too long to limit, it just slices em up to the limit with an ellipsis "..."
*
* @param $paragraph - The text you want to Parse
* @param $limit - The maximum character length, e.g. 160 chars for SMS
* @param string $delimiter - Use ' ' for words and '. ' for sentences (abbreviation bug) :)
* @param null $ellipsis - Use '...' or ' (more)' - Still respects character limit
*
* @return string
*/
function get_words_until($paragraph, $limit, $delimiter = ' ', $ellipsis = null)
{
$parts = explode($delimiter, $paragraph);
$preview = "";
if ($ellipsis) {
$limit = $limit - strlen($ellipsis);
}
foreach ($parts as $part) {
$to_add = $part . $delimiter;
if (strlen($preview . trim($to_add)) <= $limit) { // Can the part fit?
$preview .= $to_add;
continue;
}
if (!strlen($preview)) { // Is preview blank?
$preview = substr($part, 0, $limit - 3) . '...'; // Forced ellipsis
break;
}
}
return trim($preview) . $ellipsis;
}
In your case it would be (example):
在你的情况下是(例子):
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"
$small = get_words_until($big, 100);
#11
2
function truncate ($str, $length) {
if (strlen($str) > $length) {
$str = substr($str, 0, $length+1);
$pos = strrpos($str, ' ');
$str = substr($str, 0, ($pos > 0)? $pos : $length);
}
return $str;
}
Example:
例子:
print truncate('The first step to eternal life is you have to die.', 25);
string(25) "The first step to eternal"
字符串(25)"通向永恒的第一步"
print truncate('The first step to eternal life is you have to die.', 12);
string(9) "The first"
字符串(9)“第一”
print truncate('FirstStepToEternalLife', 5);
string(5) "First"
字符串(5)“第一”
#12
1
I apologize for resurrecting this question but I stumbled upon this thread and found a small issue. For anyone wanting a character limit that will remove words that would go above your given limit, the above answers work great. In my specific case, I like to display a word if the limit falls in the middle of said word. I decided to share my solution in case anyone else is looking for this functionality and needs to include words instead of trimming them out.
我为这个问题的复活道歉,但我无意中发现了这个问题,发现了一个小问题。对于任何想要字符限制的人来说,如果想要删除超出你给定限制的单词,上面的答案非常有用。在我的具体例子中,如果限制位于所述单词的中间,我喜欢显示一个单词。我决定分享我的解决方案,以防其他人正在寻找这个功能,并需要包含单词,而不是删除它们。
function str_limit($str, $len = 100, $end = '...')
{
if(strlen($str) < $len)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if(strlen($str) <= $len)
{
return $str;
}
$out = '';
foreach(explode(' ', trim($str)) as $val)
{
$out .= $val . ' ';
if(strlen($out) >= $len)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out . $end;
}
}
}
Examples:
例子:
- Input:
echo str_limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 100, '...');
- 输入:echo str_limit(Lorem ipsum dolor sit amet, committed adipisting elit, sed do eiusmod tempor incididunt ut le and dolore magna aliqua)。“,100年,“…”);
- Output:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
- 输出:Lorem ipsum ipsum dolor sit amet, committed adipisting elit, do eiusmod tempor inciddunt ut…
- Input:
echo str_limit('Lorem ipsum', 100, '...');
- 输入:echo str_limit('Lorem ipsum', 100, '…');
- Output:
Lorem ipsum
- 输出:Lorem ipsum
- Input:
echo str_limit('Lorem ipsum', 1, '...');
- 输入:echo str_limit('Lorem ipsum', 1, '…');
- Output:
Lorem...
- 输出:Lorem……
#13
1
Here is another way you can do that.
这是另一种方法。
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"
$big = trim( $big );
$small = $big;
if( strlen( $big ) > 100 ){
$small = mb_substr( $small, 0, 100 );
$last_position = mb_strripos( $small, ' ' );
if( $last_position > 0 ){
$small = mb_substr( $small, 0, $last_position );
}
}
echo $small;
OR
或
echo ( strlen( $small ) < strlen( $big ) ? $small.'...' : $small );
This is also multibyte safe and also works even if there are not spaces, in which case it will just simply return first 100 characters. It takes the first 100 characters and then searches from the end till the nearest word delimiter.
这也是多字节安全的,即使没有空格也可以使用,在这种情况下,它只返回前100个字符。它取前100个字符,然后从末尾搜索到最近的单词分隔符。
#14
1
The problem with accepted answer is that result string goes over the the limit, i.e. it can exceed 100 chars since strpos
will look after the offset and so your length will always be a over your limit. If the last word is long, like squirreled
then the length of your result will be 111 (to give you an idea).
被接受的答案的问题是,结果字符串超过了限制,也就是说,它可以超过100个字符,因为strpos将会检查偏移量,所以你的长度总是超过你的极限。如果最后一个词很长,就像交错的一样,那么结果的长度将是111(给你一个概念)。
A better solution is to use wordwrap
function:
更好的解决方案是使用wordwrap函数:
function truncate($str, $length = 125, $append = '...') {
if (strlen($str) > $length) {
$delim = "~\n~";
$str = substr($str, 0, strpos(wordwrap($str, $length, $delim), $delim)) . $append;
}
return $str;
}
echo truncate("The quick brown fox jumped over the lazy dog.", 5);
This way you can be sure the string is truncated under your limit (and never goes over)
通过这种方式,您可以确保字符串在您的限制下被截断(并且永远不会重复)
P.S. This is particularly useful if you plan to store the truncated string in your database with a fixed-with column like VARCHAR(50), etc.
如果您打算在数据库中使用固定的列(如VARCHAR(50)等)来存储截断的字符串,那么这将非常有用。
P.P.S. Note the special delimiter in wordwrap. This is to make sure that your string is truncated correctly even when it contains newlines (otherwise it will truncate at first newline which you don't want).
注:特殊分隔符用单字包装。这是为了确保您的字符串被正确地截断,即使它包含了换行符(否则它将在第一个换行符处截断,而您并不需要换行符)。
#15
1
Another a simpler way I do.
另一种更简单的方法。
function limit_words($string, $word_limit = 10)
{
$words = explode(" ", $string);
if (count($words) > $word_limit) {
return implode(" ", array_splice($words, 0, $word_limit)) . ' ...';
}
return implode(" ", array_splice($words, 0, $word_limit));
}
#16
0
wordwrap formats string according to limit, seprates them with \n so we have lines smaller than 50, ords are not seprated explodes seprates string according to \n so we have array corresponding to lines list gathers first element.
wordwrap格式字符串根据限制,将它们与\n分离,因此我们有小于50的行,ord不是根据\n分离的爆炸性字符串,所以我们有与lines列表相对应的数组,收集第一个元素。
list($short) = explode("\n",wordwrap($ali ,50));
列表(美元)=爆炸(“\ n”,自动换行(ali美元,50));
please rep Evert, since I cant comment or rep.
请代表Evert,因为我不能评论或代表。
here is sample run
这是样本运行
php > $ali = "ali veli krbin yz doksan esikesiksld sjkas laksjald lksjd asldkjadlkajsdlakjlksjdlkaj aslkdj alkdjs akdljsalkdj ";
php > list($short) = explode("\n",wordwrap($ali ,50));
php > var_dump($short);
string(42) "ali veli krbin yz doksan esikesiksld sjkas"
php > $ali ='';
php > list($short) = explode("\n",wordwrap($ali ,50));
php > var_dump($short);
string(0) ""
#17
0
Yet another answer! I wasn't completely satisfied with other answers, and wanted a 'hard cutoff' (guaranteed word break before $max_characters, if possible), so here's my function to contribute!
另一个答案!我对其他答案并不完全满意,我想要一个“硬截止”(如果可能的话,在$max_characters之前保证有断字),所以这里是我要贡献的函数!
/**
* Shortens a string (if necessary), trying for a non-word character before character limit, adds an ellipsis and
* returns. Falls back to a forced cut if no non-word characters exist before.
*
* @param string $content
* @param int $max_characters - number of characters to start looking for a space / break.
* @param bool $add_ellipsis - add ellipsis if content is shortened
*
* @return string
*/
public static function shorten( $content, $max_characters = 100, $add_ellipsis = TRUE ) {
if ( strlen( $content ) <= $max_characters ) {
return $content;
}
// search for non-word characters
$match_count = preg_match_all( '/\W/', $content, $matches, PREG_OFFSET_CAPTURE );
// force a hard break if can't find another good solution
$pos = $max_characters;
if ( $match_count > 0 ) {
foreach ( $matches[0] as $match ) {
// check if new position fits within
if ( $match[1] <= $max_characters ) {
$pos = $match[1];
} else {
break;
}
}
}
$suffix = ( $add_ellipsis ) ? '…' : '';
return substr( $content, 0, $pos ) . $suffix;
}
#18
0
## Get first limited character from a string ##
从字符串##中获取第一个有限的字符
<?php
$content= $row->title;
$result = substr($content, 0, 70);
echo $result;
?>
#1
114
All you need to do is use:
你所需要做的就是:
$pos=strpos($content, ' ', 200);
substr($content,0,$pos );
#2
31
Yes, there is. This is a function I borrowed from a user on a different forums a a few years back, so I can't take credit for it.
是的,有。这是几年前我从另一个论坛上的用户那里借来的一个功能,所以我不能把它当成自己的功劳。
//truncate a string only at a whitespace (by nogdog)
function truncate($text, $length) {
$length = abs((int)$length);
if(strlen($text) > $length) {
$text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
}
return($text);
}
Note that it automatically adds ellipses, if you don't want that just use '\\1'
as the second parameter for the preg_replace
call.
注意,如果您不希望使用“\1”作为preg_replace调用的第二个参数,它会自动添加省略号。
#3
20
If you define words as "sequences of characters delimited by space"... Use strrpos()
to find the last space in the string, shorten to that position, trim the result.
如果你将单词定义为“由空间分隔的字符序列”……使用strrpos()查找字符串中的最后一个空格,缩短到该位置,调整结果。
#4
13
Sure. The easiest is probably to write a wrapper around preg_match:
确定。最简单的方法可能是围绕preg_match编写一个包装:
function limitString($string, $limit = 100) {
// Return early if the string is already shorter than the limit
if(strlen($string) < $limit) {return $string;}
$regex = "/(.{1,$limit})\b/";
preg_match($regex, $string, $matches);
return $matches[1];
}
EDIT : Updated to not ALWAYS include a space as the last character in the string
编辑:更新为不总是包含空格作为字符串中的最后一个字符
#5
10
This function shortens a string by adding "..."
at a word boundary whenever possible. The returned string will have a maximum length of $len
including "..."
.
这个函数通过在一个单词边界添加“…”来缩短一个字符串。返回的字符串的最大长度为$len,包括“…”。
function truncate($str, $len) {
$tail = max(0, $len-10);
$trunk = substr($str, 0, $tail);
$trunk .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len-$tail))));
return $trunk;
}
Examples outputs:
例子的输出:
-
truncate("Thanks for contributing an answer to Stack Overflow!", 15)
returns"Thanks for..."
- 截断(“感谢您为Stack Overflow提供一个答案!”)“谢谢你……”
-
truncate("To learn more, see our tips on writing great answers.", 15)
returns"To learn more..."
(comma also truncated) - 截短(“要了解更多,请参阅我们写好答案的技巧。”“为了学到更多……”(逗号也截断)
-
truncate("Pseudopseudohypoparathyroidism", 15)
returns"Pseudopseudo..."
- 截断(“Pseudopseudohypoparathyroidism”,15)返回“Pseudopseudo……”
#6
6
This is my approach, based on amir's answer, but it doesn't let any word make the string longer than the limit, by using strrpos() with a negative offset.
这是我的方法,基于amir的答案,但是它不允许任何单词使字符串超过限制,使用带有负偏移量的strrpos()。
Simple but works. I'm using the same syntax as in Laravel's str_limit() helper function, in case you want to use it on a non-Laravel project.
简单而有效。我使用的语法与Laravel的str_limit() helper函数相同,以防您想在非Laravel项目上使用它。
function str_limit($value, $limit = 100, $end = '...')
{
$limit = $limit - mb_strlen($end); // Take into account $end string into the limit
$valuelen = mb_strlen($value);
return $limit < $valuelen ? mb_substr($value, 0, mb_strrpos($value, ' ', $limit - $valuelen)) . $end : $value;
}
#7
4
This works fine for me, I use it in my script
这对我来说很好,我在脚本中使用它
<?PHP
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!";
$small = some_function($big);
echo $small;
function some_function($string){
$string = substr($string,0,100);
$string = substr($string,0,strrpos($string," "));
return $string;
}
?>
good luck
祝你好运
#8
4
Here is great solution with dotts at the end with full words
这里有一个伟大的解决方案与dotts结尾的全文
function text_cut($text, $length = 200, $dots = true) {
$text = trim(preg_replace('#[\s\n\r\t]{2,}#', ' ', $text));
$text_temp = $text;
while (substr($text, $length, 1) != " ") { $length++; if ($length > strlen($text)) { break; } }
$text = substr($text, 0, $length);
return $text . ( ( $dots == true && $text != '' && strlen($text_temp) > $length ) ? '...' : '');
}
Input: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
输入:Lorem ipsum ipsum dolor sit amet, committed adipisicing elit, sed do eiusmod tempincior didunt ut le and dolore magna aliqua。但是,如果你的工作是你的工作,那么你的工作就会变得很好。这是一份来自欧盟的报告。但是,在没有任何证据的情况下,我们可以用它来证明我的工作。
Output: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip...
输出:Lorem ipsum ipsum dolor sit amet, committed adipisicing elit, sed do eiusmod tempincior didunt ut le and dolore magna aliqua。如果您有更好的听力原文,欢迎提供给大耳朵,如果被采用,您将获得20到100金币的奖励!
#9
2
This did it for me...
这是为了我……
//trim message to 100 characters, regardless of where it cuts off
$msgTrimmed = mb_substr($var,0,100);
//find the index of the last space in the trimmed message
$lastSpace = strrpos($msgTrimmed, ' ', 0);
//now trim the message at the last space so we don't cut it off in the middle of a word
echo mb_substr($msgTrimmed,0,$lastSpace)
#10
2
Here's my solution:
这是我的解决方案:
/**
* get_words_until() Returns a string of delimited text parts up to a certain length
* If the "words" are too long to limit, it just slices em up to the limit with an ellipsis "..."
*
* @param $paragraph - The text you want to Parse
* @param $limit - The maximum character length, e.g. 160 chars for SMS
* @param string $delimiter - Use ' ' for words and '. ' for sentences (abbreviation bug) :)
* @param null $ellipsis - Use '...' or ' (more)' - Still respects character limit
*
* @return string
*/
function get_words_until($paragraph, $limit, $delimiter = ' ', $ellipsis = null)
{
$parts = explode($delimiter, $paragraph);
$preview = "";
if ($ellipsis) {
$limit = $limit - strlen($ellipsis);
}
foreach ($parts as $part) {
$to_add = $part . $delimiter;
if (strlen($preview . trim($to_add)) <= $limit) { // Can the part fit?
$preview .= $to_add;
continue;
}
if (!strlen($preview)) { // Is preview blank?
$preview = substr($part, 0, $limit - 3) . '...'; // Forced ellipsis
break;
}
}
return trim($preview) . $ellipsis;
}
In your case it would be (example):
在你的情况下是(例子):
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"
$small = get_words_until($big, 100);
#11
2
function truncate ($str, $length) {
if (strlen($str) > $length) {
$str = substr($str, 0, $length+1);
$pos = strrpos($str, ' ');
$str = substr($str, 0, ($pos > 0)? $pos : $length);
}
return $str;
}
Example:
例子:
print truncate('The first step to eternal life is you have to die.', 25);
string(25) "The first step to eternal"
字符串(25)"通向永恒的第一步"
print truncate('The first step to eternal life is you have to die.', 12);
string(9) "The first"
字符串(9)“第一”
print truncate('FirstStepToEternalLife', 5);
string(5) "First"
字符串(5)“第一”
#12
1
I apologize for resurrecting this question but I stumbled upon this thread and found a small issue. For anyone wanting a character limit that will remove words that would go above your given limit, the above answers work great. In my specific case, I like to display a word if the limit falls in the middle of said word. I decided to share my solution in case anyone else is looking for this functionality and needs to include words instead of trimming them out.
我为这个问题的复活道歉,但我无意中发现了这个问题,发现了一个小问题。对于任何想要字符限制的人来说,如果想要删除超出你给定限制的单词,上面的答案非常有用。在我的具体例子中,如果限制位于所述单词的中间,我喜欢显示一个单词。我决定分享我的解决方案,以防其他人正在寻找这个功能,并需要包含单词,而不是删除它们。
function str_limit($str, $len = 100, $end = '...')
{
if(strlen($str) < $len)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if(strlen($str) <= $len)
{
return $str;
}
$out = '';
foreach(explode(' ', trim($str)) as $val)
{
$out .= $val . ' ';
if(strlen($out) >= $len)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out . $end;
}
}
}
Examples:
例子:
- Input:
echo str_limit('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 100, '...');
- 输入:echo str_limit(Lorem ipsum dolor sit amet, committed adipisting elit, sed do eiusmod tempor incididunt ut le and dolore magna aliqua)。“,100年,“…”);
- Output:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore...
- 输出:Lorem ipsum ipsum dolor sit amet, committed adipisting elit, do eiusmod tempor inciddunt ut…
- Input:
echo str_limit('Lorem ipsum', 100, '...');
- 输入:echo str_limit('Lorem ipsum', 100, '…');
- Output:
Lorem ipsum
- 输出:Lorem ipsum
- Input:
echo str_limit('Lorem ipsum', 1, '...');
- 输入:echo str_limit('Lorem ipsum', 1, '…');
- Output:
Lorem...
- 输出:Lorem……
#13
1
Here is another way you can do that.
这是另一种方法。
$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"
$big = trim( $big );
$small = $big;
if( strlen( $big ) > 100 ){
$small = mb_substr( $small, 0, 100 );
$last_position = mb_strripos( $small, ' ' );
if( $last_position > 0 ){
$small = mb_substr( $small, 0, $last_position );
}
}
echo $small;
OR
或
echo ( strlen( $small ) < strlen( $big ) ? $small.'...' : $small );
This is also multibyte safe and also works even if there are not spaces, in which case it will just simply return first 100 characters. It takes the first 100 characters and then searches from the end till the nearest word delimiter.
这也是多字节安全的,即使没有空格也可以使用,在这种情况下,它只返回前100个字符。它取前100个字符,然后从末尾搜索到最近的单词分隔符。
#14
1
The problem with accepted answer is that result string goes over the the limit, i.e. it can exceed 100 chars since strpos
will look after the offset and so your length will always be a over your limit. If the last word is long, like squirreled
then the length of your result will be 111 (to give you an idea).
被接受的答案的问题是,结果字符串超过了限制,也就是说,它可以超过100个字符,因为strpos将会检查偏移量,所以你的长度总是超过你的极限。如果最后一个词很长,就像交错的一样,那么结果的长度将是111(给你一个概念)。
A better solution is to use wordwrap
function:
更好的解决方案是使用wordwrap函数:
function truncate($str, $length = 125, $append = '...') {
if (strlen($str) > $length) {
$delim = "~\n~";
$str = substr($str, 0, strpos(wordwrap($str, $length, $delim), $delim)) . $append;
}
return $str;
}
echo truncate("The quick brown fox jumped over the lazy dog.", 5);
This way you can be sure the string is truncated under your limit (and never goes over)
通过这种方式,您可以确保字符串在您的限制下被截断(并且永远不会重复)
P.S. This is particularly useful if you plan to store the truncated string in your database with a fixed-with column like VARCHAR(50), etc.
如果您打算在数据库中使用固定的列(如VARCHAR(50)等)来存储截断的字符串,那么这将非常有用。
P.P.S. Note the special delimiter in wordwrap. This is to make sure that your string is truncated correctly even when it contains newlines (otherwise it will truncate at first newline which you don't want).
注:特殊分隔符用单字包装。这是为了确保您的字符串被正确地截断,即使它包含了换行符(否则它将在第一个换行符处截断,而您并不需要换行符)。
#15
1
Another a simpler way I do.
另一种更简单的方法。
function limit_words($string, $word_limit = 10)
{
$words = explode(" ", $string);
if (count($words) > $word_limit) {
return implode(" ", array_splice($words, 0, $word_limit)) . ' ...';
}
return implode(" ", array_splice($words, 0, $word_limit));
}
#16
0
wordwrap formats string according to limit, seprates them with \n so we have lines smaller than 50, ords are not seprated explodes seprates string according to \n so we have array corresponding to lines list gathers first element.
wordwrap格式字符串根据限制,将它们与\n分离,因此我们有小于50的行,ord不是根据\n分离的爆炸性字符串,所以我们有与lines列表相对应的数组,收集第一个元素。
list($short) = explode("\n",wordwrap($ali ,50));
列表(美元)=爆炸(“\ n”,自动换行(ali美元,50));
please rep Evert, since I cant comment or rep.
请代表Evert,因为我不能评论或代表。
here is sample run
这是样本运行
php > $ali = "ali veli krbin yz doksan esikesiksld sjkas laksjald lksjd asldkjadlkajsdlakjlksjdlkaj aslkdj alkdjs akdljsalkdj ";
php > list($short) = explode("\n",wordwrap($ali ,50));
php > var_dump($short);
string(42) "ali veli krbin yz doksan esikesiksld sjkas"
php > $ali ='';
php > list($short) = explode("\n",wordwrap($ali ,50));
php > var_dump($short);
string(0) ""
#17
0
Yet another answer! I wasn't completely satisfied with other answers, and wanted a 'hard cutoff' (guaranteed word break before $max_characters, if possible), so here's my function to contribute!
另一个答案!我对其他答案并不完全满意,我想要一个“硬截止”(如果可能的话,在$max_characters之前保证有断字),所以这里是我要贡献的函数!
/**
* Shortens a string (if necessary), trying for a non-word character before character limit, adds an ellipsis and
* returns. Falls back to a forced cut if no non-word characters exist before.
*
* @param string $content
* @param int $max_characters - number of characters to start looking for a space / break.
* @param bool $add_ellipsis - add ellipsis if content is shortened
*
* @return string
*/
public static function shorten( $content, $max_characters = 100, $add_ellipsis = TRUE ) {
if ( strlen( $content ) <= $max_characters ) {
return $content;
}
// search for non-word characters
$match_count = preg_match_all( '/\W/', $content, $matches, PREG_OFFSET_CAPTURE );
// force a hard break if can't find another good solution
$pos = $max_characters;
if ( $match_count > 0 ) {
foreach ( $matches[0] as $match ) {
// check if new position fits within
if ( $match[1] <= $max_characters ) {
$pos = $match[1];
} else {
break;
}
}
}
$suffix = ( $add_ellipsis ) ? '…' : '';
return substr( $content, 0, $pos ) . $suffix;
}
#18
0
## Get first limited character from a string ##
从字符串##中获取第一个有限的字符
<?php
$content= $row->title;
$result = substr($content, 0, 70);
echo $result;
?>