代码之家  ›  专栏  ›  技术社区  ›  Alex

获取字符串的前n个字符

  •  290
  • Alex  · 技术社区  · 14 年前

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

    18 回复  |  直到 4 年前
        1
  •  603
  •   Emil Vikström    10 年前
    //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;
    

    更新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;
    }
    
        2
  •  127
  •   user664833 Ronen Rabinovici    7 年前

    此功能自4.0.6版起就内置在PHP中。 See the docs

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

    请注意 trimmarker

        3
  •  15
  •   Emil Vikström    11 年前

    如果需要控制字符串字符集,多字节扩展就很有用。

    $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
  •  10
  •   Ankur    12 年前

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

    如: 我们需要将“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;
        }
    
    }
    
        5
  •  9
  •   Niki Romagnoli    8 年前

    如果你想切分,小心不要把单词分开,你可以做以下的操作

    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\u chars,则返回原样。

    如果$str等于$n\u chars,则返回原样。

    如果$str比$n\u chars长,那么它会寻找下一个要剪切的空间,或者(如果到最后没有更多的空间)$str会被粗暴地剪切成$n\u chars。

    请注意,对于HTML,此方法将删除所有标记。

        6
  •  8
  •   Matthew    14 年前

    codeigniter框架包含一个用于此的助手,称为“文本助手”。以下是适用于codeigniter用户指南的一些文档: http://codeigniter.com/user_guide/helpers/text_helper.html (只需阅读单词\u limiter和字符\u 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;
                }       
            }
        }
    }
    
        7
  •  3
  •   HCL    14 年前
    if(strlen($text) > 10)
         $text = substr($text,0,10) . "...";
    
        8
  •  3
  •   Dlongnecker    14 年前

    使用子字符串

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

    $foo = substr("abcde",0, 3) . "...";
    
        9
  •  1
  •   Benjamin Crouzier 8vius    13 年前

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

    看到了吗 in action .

        10
  •  1
  •   christoz    12 年前

    我就是这么做的

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

    其中,$num表示字符数,$tt表示操纵字符串。

        11
  •  1
  •   Ankur    12 年前

    我为此开发了一个函数

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


    如: str_short("hahahahahah",5) ;
    它会切断你的绳子,在最后加上“…”
    :)

        12
  •  1
  •   tfont    11 年前

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

    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
  •   TravisO    11 年前

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

    print limit($string);
    
    
    function limit($var, $limit=10)
    {
        if ( strlen($var) > $limit )
        {
            return substr($string, 0, $limit) . '...';
        }
        else
        {
            return $var;
        }
    }
    
        14
  •  1
  •   Community CDub    7 年前

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

    请看这里的一些例子 https://stackoverflow.com/a/17852480/131337

        15
  •  0
  •   tsgrasser    14 年前

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

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

        16
  •  0
  •   akond    11 年前

    $width=10;

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

    $a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
    
        17
  •  0
  •   Waqleh    11 年前

    这个解决方案不会删减文字,它会在第一个空格后加上三个点。 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
  •   Jaykishan    11 年前
    $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;
    
        19
  •  0
  •   jim_kastrin    4 年前

    如果对被截断字符串的长度没有严格要求,则可以使用此命令来截断并防止截断最后一个单词:

    $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