php 获取字符串的前 n 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3161816/
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 n characters of a string
提问by Alex
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 个字符?将字符串修剪为特定数量的字符并在需要时附加“...”的最快方法是什么?
回答by Brendan Bullen
//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 wordwrapfunction:
我写这个答案已经有一段时间了,我实际上不再使用这个代码了。我更喜欢这个功能,它可以使用以下功能防止在单词中间破坏字符串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;
}
回答by bruchowski
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(上面的省略号)包含在截断长度中。
回答by Emil Vikstr?m
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) . '...';
}
回答by MortalViews
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.
例如:我们需要将“这是我的字符串”限制为 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;
}
}
回答by TechNyquist
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 中的所有标签。
回答by Matthew
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;
}
}
}
}
回答by Dlongnecker
Use substring
使用子串
http://php.net/manual/en/function.substr.php
http://php.net/manual/en/function.substr.php
$foo = substr("abcde",0, 3) . "...";
回答by HCL
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
回答by TravisO
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;
}
}

