php 从字符串中获取前 100 个字符,尊重完整单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/972010/
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
Get first 100 characters from string, respecting full words
提问by JoshFinnie
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);
echo $small;
// OUTPUT: "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 做到这一点?
回答by amir
All you need to do is use:
您需要做的就是使用:
$pos=strpos($content, ' ', 200);
substr($content,0,$pos );
回答by TJ L
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_replacecall.
请注意,它会自动添加省略号,如果您不想将其'\\1'用作preg_replace调用的第二个参数。
回答by Tomalak
回答by PatrikAkerstrand
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
编辑:更新为不总是包含一个空格作为字符串中的最后一个字符
回答by OMA
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() 辅助函数相同的语法,以防您想在非 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;
}
回答by filip
This function shortens a string by adding "..."at a word boundary whenever possible. The returned string will have a maximum length of $lenincluding "...".
此函数通过"..."尽可能在单词边界处添加来缩短字符串。返回的字符串的最大长度为$lenincludes "..."。
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..."truncate("To learn more, see our tips on writing great answers.", 15)
returns"To learn more..."(comma also truncated)truncate("Pseudopseudohypoparathyroidism", 15)
returns"Pseudopseudo..."
truncate("Thanks for contributing an answer to Stack Overflow!", 15)
返回"Thanks for..."truncate("To learn more, see our tips on writing great answers.", 15)
返回"To learn more..."(逗号也被截断)truncate("Pseudopseudohypoparathyroidism", 15)
返回"Pseudopseudo..."
回答by Arek - Krakiewicz.pl
Here is great solution with dotts at the end with full words
这是一个很好的解决方案,最后有一个完整的单词
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 dolor sat 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。例外 sint occaecat cupidatat non proident, 在 culpa qui offcia deserunt mollit anim id est labourum 中被禁止。
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 dolor sat amet、consectetur adipisicing elit、sed do eiusmod tempor incididunt ut Labore et dolore magna aliqua。Ut enim ad minim veniam, quis nostrud exeritation ullamco Laboris nisi ut aliquip...
回答by ahmed
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
祝你好运
回答by supersan
The problem with accepted answer is that result string goes over the the limit, i.e. it can exceed 100 chars since strposwill look afterthe offset and so your length will always be a over your limit. If the last word is long, like squirreledthen the length of your result will be 111 (to give you an idea).
公认的答案的问题是,结果字符串越过极限,即它可以超过100个字符,因为strpos会看后偏移等你的长度总是会在你的极限。如果最后一个字很长,squirreled那么你的结果的长度将是 111(给你一个想法)。
A better solution is to use wordwrapfunction:
更好的解决方案是使用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.
PS如果您打算使用 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).
PPS注意自动换行中的特殊分隔符。这是为了确保您的字符串即使包含换行符也能被正确截断(否则它会在您不想要的第一个换行符处截断)。
回答by Aigars Matulis
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"
string(25) "通往永恒的第一步"
print truncate('The first step to eternal life is you have to die.', 12);
string(9) "The first"
string(9) "第一个"
print truncate('FirstStepToEternalLife', 5);
string(5) "First"
字符串(5)“第一个”

