How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?
如何在PHP中获得字符串的前n个字符?将字符串裁剪成特定数量的字符的最快方法是什么?“如果需要吗?
18 个解决方案
#1
488
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
更新:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
根据检查长度的建议(并确保修剪和未修剪的字符串具有类似的长度):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
你会得到一个最多13个字符的字符串;13个(或更少)正常字符或10个字符后跟“…”
Update 2:
更新2:
Or as function:
或功能:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
更新3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap
function:
我写这个答案已经有一段时间了,实际上我不再使用这个代码了。我更喜欢这个函数,它可以防止使用wordwrap函数在单词中间破坏字符串:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
#2
98
This functionality has been built into PHP since version 4.0.6. See the docs.
自版本4.0.6以来,这个功能已经被构建到PHP中。看文档。
echo mb_strimwidth('Hello World', 0, 10, '...');
// outputs Hello W...
Note that the trimmarker
(the ellipsis above) are included in the truncated length.
注意,trimmarker(上面的省略号)包含在截断长度中。
#3
14
The Multibyte extension can come in handy if you need control over the string charset.
如果需要控制字符串字符集,那么多字节扩展可以派上用场。
$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) {
$string = mb_substr($string, 0, $length - 3, $charset) . '...';
}
#4
9
sometimes, you need to limit the string to the last complete word ie: you don't want the last word to be broken instead you stop with the second last word.
有时,你需要将字符串限制为最后一个完整的单词:你不希望最后一个单词被破坏,而是用第二个单词结束。
eg: we need to limit "This is my String" to 6 chars but instead of 'This i..." we want it to be 'This..." ie we will skip that broken letters in the last word.
我们需要将"This is my String"限制在6个字符,而不是"This i…"我们希望它是"This…"(我们将跳过最后一个单词中出现的破折号。)
phew, am bad at explaining, here is the code.
哎呀,我不善于解释,这是代码。
class Fun {
public function limit_text($text, $len) {
if (strlen($text) < $len) {
return $text;
}
$text_words = explode(' ', $text);
$out = null;
foreach ($text_words as $word) {
if ((strlen($word) > $len) && $out == null) {
return substr($word, 0, $len) . "...";
}
if ((strlen($out) + strlen($word)) > $len) {
return $out . "...";
}
$out.=" " . $word;
}
return $out;
}
}
#5
7
The codeigniter framework contains a helper for this, called the "text helper". Here's some documentation from codeigniter's user guide that applies: http://codeigniter.com/user_guide/helpers/text_helper.html (just read the word_limiter and character_limiter sections). Here's two functions from it relevant to your question:
codeigniter框架包含一个助手,称为“文本助手”。下面是codeigniter的用户指南中的一些文档,它适用于:http://codeigniter.com/user_guide/helpers/text_helper.html(只需阅读word_limiter和character_limiter部分)。这里有两个与你的问题相关的功能:
if ( ! function_exists('word_limiter'))
{
function word_limiter($str, $limit = 100, $end_char = '…')
{
if (trim($str) == '')
{
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = '';
}
return rtrim($matches[0]).$end_char;
}
}
And
和
if ( ! function_exists('character_limiter'))
{
function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if (strlen($str) <= $n)
{
return $str;
}
$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
}
}
}
}
#6
7
If you want to cut being careful to don't split words you can do the following
如果你想要切分的话,你可以做以下的事情
function ellipse($str,$n_chars,$crop_str=' [...]')
{
$buff=strip_tags($str);
if(strlen($buff) > $n_chars)
{
$cut_index=strpos($buff,' ',$n_chars);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
}
return $buff;
}
if $str is shorter than $n_chars returns it untouched.
如果$str小于$n_chars,则返回未受影响的值。
If $str is equal to $n_chars returns it as is as well.
如果$str等于$n_chars,则返回它本身。
if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.
如果$str大于$n_chars,那么它会寻找下一个要剪切的空间,或者(如果在结束之前没有更多的空间的话)$str会在$n_chars处被粗鲁地剪切。
NOTE: be aware that this method will remove all tags in case of HTML.
注意:请注意,如果是HTML,此方法将删除所有标记。
#7
4
Use substring
使用子串
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.substr.php
$foo = substr("abcde",0, 3) . "...";
#8
2
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
#9
1
The function I used:
使用的函数:
function cutAfter($string, $len = 30, $append = '...') {
return (strlen($string) > $len) ?
substr($string, 0, $len - strlen($append)) . $append :
$string;
}
See it in action.
看它的实际应用。
#10
1
This is what i do
这就是我所做的。
function cutat($num, $tt){
if (mb_strlen($tt)>$num){
$tt=mb_substr($tt,0,$num-2).'...';
}
return $tt;
}
where $num stands for number of chars, and $tt the string for manipulation.
其中$num表示字符数,$tt用于操作。
#11
1
I developed a function for this use
我为此开发了一个函数
function str_short($string,$limit)
{
$len=strlen($string);
if($len>$limit)
{
$to_sub=$len-$limit;
$crop_temp=substr($string,0,-$to_sub);
return $crop_len=$crop_temp."...";
}
else
{
return $string;
}
}
you just call the function with string and limite
eg:str_short("hahahahahah",5)
;
it will cut of your string and add "..." at the end
:)
你只需用string和limite调用函数例如:str_short(“hahahahahahaha”,5);它会把你的线剪断,然后加上“…”
#12
1
To create within a function (for repeat usage) and dynamical limited length, use:
要在函数(用于重复使用)和动态有限长度内创建,请使用:
function string_length_cutoff($string, $limit, $subtext = '...')
{
return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}
// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
#13
1
It's best to abstract you're code like so (notice the limit is optional and defaults to 10):
最好把你的代码抽象成这样(注意限制是可选的,默认为10):
print limit($string);
function limit($var, $limit=10)
{
if ( strlen($var) > $limit )
{
return substr($string, 0, $limit) . '...';
}
else
{
return $var;
}
}
#14
1
I'm not sure if this is the fastest solution, but it looks like it is the shortest one:
我不确定这是否是最快的解,但看起来它是最短的解:
$result = current(explode("\n", wordwrap($str, $width, "...\n")));
P.S. See some examples here https://*.com/a/17852480/131337
这里有一些例子,https://*.com/a/17852480/131337
#15
0
substr() would be best, you'll also want to check the length of the string first
substr()是最好的,您还需要首先检查字符串的长度。
$str = 'someLongString';
$max = 7;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...';
}
wordwrap won't trim the string down, just split it up...
wordwrap不会对字符串进行修剪,只是将其拆分……
#16
0
$width = 10;
宽度= 10美元;
$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);
or with wordwrap
或自动换行
$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
#17
0
this solution will not cut words, it will add three dots after the first space. I edited @Raccoon29 solution and I replaced all functions with mb_ functions so that this will work for all languages such as arabic
这个解决方案不会减少单词,它会在第一个空格后加3个点。我编辑了@Raccoon29解决方案,我用mb_函数替换了所有函数,这样就可以在所有语言(比如阿拉伯语)上使用了
function cut_string($str, $n_chars, $crop_str = '...') {
$buff = strip_tags($str);
if (mb_strlen($buff) > $n_chars) {
$cut_index = mb_strpos($buff, ' ', $n_chars);
$buff = mb_substr($buff, 0, ($cut_index === false ? $n_chars : $cut_index + 1), "UTF-8") . $crop_str;
}
return $buff;
}
#18
0
$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
while(strlen($yourString) > 22) {
$pos = strrpos($yourString, " ");
if($pos !== false && $pos <= 22) {
$out = substr($yourString,0,$pos);
break;
} else {
$yourString = substr($yourString,0,$pos);
continue;
}
}
} else {
$out = $yourString;
}
echo "Output String: ".$out;
#1
488
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
Update:
更新:
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
根据检查长度的建议(并确保修剪和未修剪的字符串具有类似的长度):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
你会得到一个最多13个字符的字符串;13个(或更少)正常字符或10个字符后跟“…”
Update 2:
更新2:
Or as function:
或功能:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
Update 3:
更新3:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap
function:
我写这个答案已经有一段时间了,实际上我不再使用这个代码了。我更喜欢这个函数,它可以防止使用wordwrap函数在单词中间破坏字符串:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
#2
98
This functionality has been built into PHP since version 4.0.6. See the docs.
自版本4.0.6以来,这个功能已经被构建到PHP中。看文档。
echo mb_strimwidth('Hello World', 0, 10, '...');
// outputs Hello W...
Note that the trimmarker
(the ellipsis above) are included in the truncated length.
注意,trimmarker(上面的省略号)包含在截断长度中。
#3
14
The Multibyte extension can come in handy if you need control over the string charset.
如果需要控制字符串字符集,那么多字节扩展可以派上用场。
$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) {
$string = mb_substr($string, 0, $length - 3, $charset) . '...';
}
#4
9
sometimes, you need to limit the string to the last complete word ie: you don't want the last word to be broken instead you stop with the second last word.
有时,你需要将字符串限制为最后一个完整的单词:你不希望最后一个单词被破坏,而是用第二个单词结束。
eg: we need to limit "This is my String" to 6 chars but instead of 'This i..." we want it to be 'This..." ie we will skip that broken letters in the last word.
我们需要将"This is my String"限制在6个字符,而不是"This i…"我们希望它是"This…"(我们将跳过最后一个单词中出现的破折号。)
phew, am bad at explaining, here is the code.
哎呀,我不善于解释,这是代码。
class Fun {
public function limit_text($text, $len) {
if (strlen($text) < $len) {
return $text;
}
$text_words = explode(' ', $text);
$out = null;
foreach ($text_words as $word) {
if ((strlen($word) > $len) && $out == null) {
return substr($word, 0, $len) . "...";
}
if ((strlen($out) + strlen($word)) > $len) {
return $out . "...";
}
$out.=" " . $word;
}
return $out;
}
}
#5
7
The codeigniter framework contains a helper for this, called the "text helper". Here's some documentation from codeigniter's user guide that applies: http://codeigniter.com/user_guide/helpers/text_helper.html (just read the word_limiter and character_limiter sections). Here's two functions from it relevant to your question:
codeigniter框架包含一个助手,称为“文本助手”。下面是codeigniter的用户指南中的一些文档,它适用于:http://codeigniter.com/user_guide/helpers/text_helper.html(只需阅读word_limiter和character_limiter部分)。这里有两个与你的问题相关的功能:
if ( ! function_exists('word_limiter'))
{
function word_limiter($str, $limit = 100, $end_char = '…')
{
if (trim($str) == '')
{
return $str;
}
preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $str, $matches);
if (strlen($str) == strlen($matches[0]))
{
$end_char = '';
}
return rtrim($matches[0]).$end_char;
}
}
And
和
if ( ! function_exists('character_limiter'))
{
function character_limiter($str, $n = 500, $end_char = '…')
{
if (strlen($str) < $n)
{
return $str;
}
$str = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $str));
if (strlen($str) <= $n)
{
return $str;
}
$out = "";
foreach (explode(' ', trim($str)) as $val)
{
$out .= $val.' ';
if (strlen($out) >= $n)
{
$out = trim($out);
return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
}
}
}
}
#6
7
If you want to cut being careful to don't split words you can do the following
如果你想要切分的话,你可以做以下的事情
function ellipse($str,$n_chars,$crop_str=' [...]')
{
$buff=strip_tags($str);
if(strlen($buff) > $n_chars)
{
$cut_index=strpos($buff,' ',$n_chars);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
}
return $buff;
}
if $str is shorter than $n_chars returns it untouched.
如果$str小于$n_chars,则返回未受影响的值。
If $str is equal to $n_chars returns it as is as well.
如果$str等于$n_chars,则返回它本身。
if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.
如果$str大于$n_chars,那么它会寻找下一个要剪切的空间,或者(如果在结束之前没有更多的空间的话)$str会在$n_chars处被粗鲁地剪切。
NOTE: be aware that this method will remove all tags in case of HTML.
注意:请注意,如果是HTML,此方法将删除所有标记。
#7
4
Use substring
使用子串
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.substr.php
$foo = substr("abcde",0, 3) . "...";
#8
2
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
#9
1
The function I used:
使用的函数:
function cutAfter($string, $len = 30, $append = '...') {
return (strlen($string) > $len) ?
substr($string, 0, $len - strlen($append)) . $append :
$string;
}
See it in action.
看它的实际应用。
#10
1
This is what i do
这就是我所做的。
function cutat($num, $tt){
if (mb_strlen($tt)>$num){
$tt=mb_substr($tt,0,$num-2).'...';
}
return $tt;
}
where $num stands for number of chars, and $tt the string for manipulation.
其中$num表示字符数,$tt用于操作。
#11
1
I developed a function for this use
我为此开发了一个函数
function str_short($string,$limit)
{
$len=strlen($string);
if($len>$limit)
{
$to_sub=$len-$limit;
$crop_temp=substr($string,0,-$to_sub);
return $crop_len=$crop_temp."...";
}
else
{
return $string;
}
}
you just call the function with string and limite
eg:str_short("hahahahahah",5)
;
it will cut of your string and add "..." at the end
:)
你只需用string和limite调用函数例如:str_short(“hahahahahahaha”,5);它会把你的线剪断,然后加上“…”
#12
1
To create within a function (for repeat usage) and dynamical limited length, use:
要在函数(用于重复使用)和动态有限长度内创建,请使用:
function string_length_cutoff($string, $limit, $subtext = '...')
{
return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}
// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);
// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');
#13
1
It's best to abstract you're code like so (notice the limit is optional and defaults to 10):
最好把你的代码抽象成这样(注意限制是可选的,默认为10):
print limit($string);
function limit($var, $limit=10)
{
if ( strlen($var) > $limit )
{
return substr($string, 0, $limit) . '...';
}
else
{
return $var;
}
}
#14
1
I'm not sure if this is the fastest solution, but it looks like it is the shortest one:
我不确定这是否是最快的解,但看起来它是最短的解:
$result = current(explode("\n", wordwrap($str, $width, "...\n")));
P.S. See some examples here https://*.com/a/17852480/131337
这里有一些例子,https://*.com/a/17852480/131337
#15
0
substr() would be best, you'll also want to check the length of the string first
substr()是最好的,您还需要首先检查字符串的长度。
$str = 'someLongString';
$max = 7;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...';
}
wordwrap won't trim the string down, just split it up...
wordwrap不会对字符串进行修剪,只是将其拆分……
#16
0
$width = 10;
宽度= 10美元;
$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);
or with wordwrap
或自动换行
$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
#17
0
this solution will not cut words, it will add three dots after the first space. I edited @Raccoon29 solution and I replaced all functions with mb_ functions so that this will work for all languages such as arabic
这个解决方案不会减少单词,它会在第一个空格后加3个点。我编辑了@Raccoon29解决方案,我用mb_函数替换了所有函数,这样就可以在所有语言(比如阿拉伯语)上使用了
function cut_string($str, $n_chars, $crop_str = '...') {
$buff = strip_tags($str);
if (mb_strlen($buff) > $n_chars) {
$cut_index = mb_strpos($buff, ' ', $n_chars);
$buff = mb_substr($buff, 0, ($cut_index === false ? $n_chars : $cut_index + 1), "UTF-8") . $crop_str;
}
return $buff;
}
#18
0
$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
while(strlen($yourString) > 22) {
$pos = strrpos($yourString, " ");
if($pos !== false && $pos <= 22) {
$out = substr($yourString,0,$pos);
break;
} else {
$yourString = substr($yourString,0,$pos);
continue;
}
}
} else {
$out = $yourString;
}
echo "Output String: ".$out;