350

如何在 PHP 中获取字符串的前 n 个字符?将字符串修剪为特定数量的字符并在需要时附加“...”的最快方法是什么?

4

20 回答 20

627
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';

更新:

基于检查长度的建议(并确保修剪和未修剪的字符串的长度相似):

$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;

所以你会得到一个最多 13 个字符的字符串;13 个(或更少)普通字符或 10 个字符后跟“...”

更新 2:

或作为函数:

function truncate($string, $length, $dots = "...") {
    return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}

更新 3:

我写这个答案已经有一段时间了,我实际上不再使用这个代码了。我更喜欢这个函数,它可以防止使用该函数在单词中间破坏字符串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;
}
于 2010-07-01T21:30:17.370 回答
137

自版本 4.0.6 起,此功能已内置到 PHP 中。请参阅文档

echo mb_strimwidth('Hello World', 0, 10, '...');

// outputs Hello W...

请注意,trimmarker(上面的省略号)包含在截断长度中。

于 2014-07-03T22:56:09.353 回答
15

如果您需要控制字符串字符集,多字节扩展可以派上用场。

$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) . '...';
}
于 2010-07-01T21:35:34.330 回答
11

有时,您需要将字符串限制为最后一个完整的单词,即:您不希望最后一个单词被破坏,而是以倒数第二个单词停止。

例如:我们需要将“This is my String”限制为 6 个字符,但我们希望它不是“This i...”,而是“This...”,即我们将跳过最后一个单词中的损坏字母。

唷,我不擅长解释,这是代码。

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;
    }

}
于 2013-03-23T08:27:15.537 回答
9

如果你想切切小心不要拆分单词,你可以执行以下操作

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;
}

如果 $str 短于 $n_chars 则原封不动地返回它。

如果 $str 等于 $n_chars 也将返回它。

如果 $str 比 $n_chars 长,那么它会寻找下一个要剪切的空格,或者(如果直到最后没有更多空格)$str 会被粗鲁地剪切,而不是在 $n_chars 处。

注意:请注意,如果是 HTML,此方法将删除所有标签。

于 2013-07-17T14:45:08.180 回答
8

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 = '&#8230;')
    {
        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;
    }
}

if ( ! function_exists('character_limiter'))
{
    function character_limiter($str, $n = 500, $end_char = '&#8230;')
    {
        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;
            }       
        }
    }
}
于 2010-07-06T01:43:53.943 回答
4
if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";
于 2010-07-01T21:31:02.160 回答
3

使用子字符串

http://php.net/manual/en/function.substr.php

$foo = substr("abcde",0, 3) . "...";
于 2010-07-01T21:32:32.957 回答
1

最好像这样抽象你的代码(注意限制是可选的,默认为 10):

print limit($string);


function limit($var, $limit=10)
{
    if ( strlen($var) > $limit )
    {
        return substr($string, 0, $limit) . '...';
    }
    else
    {
        return $var;
    }
}
于 2010-07-01T21:35:12.863 回答
1

我使用的功能:

function cutAfter($string, $len = 30, $append = '...') {
        return (strlen($string) > $len) ? 
          substr($string, 0, $len - strlen($append)) . $append : 
          $string;
}

看到它在行动

于 2011-09-21T19:59:36.237 回答
1

我为此用途开发了一个功能

 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;
            }
        }

您只需使用 string 和 limite 调用该函数,
例如:str_short("hahahahahah",5);
它会切断你的字符串并在末尾添加“...”
:)

于 2013-02-04T06:08:03.240 回答
1

这就是我所做的

    function cutat($num, $tt){
        if (mb_strlen($tt)>$num){
            $tt=mb_substr($tt,0,$num-2).'...';
        }
        return $tt;
    }

其中 $num 代表字符数,$tt 是用于操作的字符串。

于 2013-03-21T16:56:42.717 回答
1

要在函数内创建(用于重复使用)和动态限制长度​​,请使用:

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, '..');
于 2013-06-19T17:03:29.677 回答
1

我不确定这是否是最快的解决方案,但看起来它是最短的解决方案:

$result = current(explode("\n", wordwrap($str, $width, "...\n")));

PS在这里查看一些示例https://stackoverflow.com/a/17852480/131337

于 2013-07-25T08:21:40.597 回答
1

此功能可以在不中断单词的情况下完成工作

    function str_trim($str,$char_no){
        if(strlen($str)<=$char_no)
            return $str;
        else{
            $all_words=explode(" ",$str);
            $out_str='';
            foreach ($all_words as $word) {
                $temp_str=($out_str=='')?$word:$out_str.' '.$word;
                if(strlen($temp_str)>$char_no-3)//-3 for 3 dots
                    return $out_str."...";
                $out_str=$temp_str;
            }
        }
    }
于 2021-08-08T10:14:43.583 回答
0

substr() 最好,您还需要先检查字符串的长度

$str = 'someLongString';
$max = 7;

if(strlen($str) > $max) {
   $str = substr($str, 0, $max) . '...';
}

wordwrap 不会修剪字符串,只是将其拆分...

于 2010-07-01T21:42:37.580 回答
0

$宽度 = 10;

$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);

或使用自动换行

$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
于 2013-07-26T15:50:59.877 回答
0

此解决方案不会削减单词,它会在第一个空格后添加三个点。我编辑了@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;
}
于 2014-01-27T13:17:50.440 回答
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;
于 2014-03-04T13:47:23.140 回答
0

如果对截断字符串的长度没有硬性要求,则可以使用它来截断并防止截断最后一个单词:

$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";

// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);

// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));

// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));

在这种情况下,$preview"Knowledge is a natural right of every human being".

实时代码示例: http ://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713

于 2020-06-15T13:00:03.670 回答