将字符串截断为字符串的前 n 个字符,如果删除了任何字符,则添加三个点

发布于 2024-09-07 21:07:52 字数 63 浏览 11 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

坏尐絯 2024-09-14 21:08:25

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

$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将是“知识是每个人的自然权利”

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

If there is no hard requirement on the length of the truncated string, one can use this to truncate and prevent cutting the last word as well:

$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, " ")));

In this case, $preview will be "Knowledge is a natural right of every human being".

Live code example:
http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713

半透明的墙 2024-09-14 21:08:24
$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;
$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;
我喜欢麦丽素 2024-09-14 21:08:22

此解决方案不会剪切单词,它会在第一个空格后添加三个点。
我编辑了 @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;
}

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

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;
}
耳根太软 2024-09-14 21:08:21

$宽度= 10;

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

或使用自动换行

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

$width = 10;

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

or with wordwrap

$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
眼泪都笑了 2024-09-14 21:08:18

substr() 是最好的,您还需要检查字符串的长度,第一个

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

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

自动换行不会修剪字符串,只需将其拆分...

substr() would be best, you'll also want to check the length of the string first

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

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

wordwrap won't trim the string down, just split it up...

岁月静好 2024-09-14 21:08:16

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

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

PS 请参阅此处的一些示例 https:// /stackoverflow.com/a/17852480/131337

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://stackoverflow.com/a/17852480/131337

岁月打碎记忆 2024-09-14 21:08:12

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

print limit($string);


function limit($var, $limit=10)
{
    if ( strlen($var) > $limit )
    {
        return substr($string, 0, $limit) . '...';
    }
    else
    {
        return $var;
    }
}

It's best to abstract you're code like so (notice the limit is optional and defaults to 10):

print limit($string);


function limit($var, $limit=10)
{
    if ( strlen($var) > $limit )
    {
        return substr($string, 0, $limit) . '...';
    }
    else
    {
        return $var;
    }
}
滿滿的愛 2024-09-14 21:08:10

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

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, '..');

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, '..');
简美 2024-09-14 21:08:08

我为此开发了一个函数,

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

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

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
:)

习惯成性 2024-09-14 21:08:06

这就是我所做的

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

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

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.

心意如水 2024-09-14 21:08:04

我使用的功能:

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

查看它实际操作

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.

牵强ㄟ 2024-09-14 21:08:02

Laravel 6+ 版本中已经有一个辅助方法。你可以简单地使用它。

\Str::limit('The quick brown fox jumps over the lazy dog', 20);

它为您提供类似的输出

The quick brown fox...

有关更多详细信息,请查看 laravel 官方文档: https: //laravel.com/docs/8.x/helpers#method-str-limit

It already has a helper method for it in Laravel 6+ versions. You could simply use that.

\Str::limit('The quick brown fox jumps over the lazy dog', 20);

which gives you output like

The quick brown fox...

For more detail please check laravel official document: https://laravel.com/docs/8.x/helpers#method-str-limit

那片花海 2024-09-14 21:08:00

这个函数可以完成工作而不会在中间中断单词

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

This function do the job without breaking words in the middle

    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;
            }
        }
    }
为你拒绝所有暧昧 2024-09-14 21:07:59

使用子字符串

http://php.net/manual/en/function.substr.php< /a>

$foo = substr("abcde",0, 3) . "...";

Use substring

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

$foo = substr("abcde",0, 3) . "...";
凉城已无爱 2024-09-14 21:07:58
if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";
if(strlen($text) > 10)
     $text = substr($text,0,10) . "...";
痕至 2024-09-14 21:07:57

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

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

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:

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;
            }       
        }
    }
}
﹎☆浅夏丿初晴 2024-09-14 21:07:56

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

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 中的所有标签。

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.

If $str is equal to $n_chars returns it as is as well.

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.

NOTE: be aware that this method will remove all tags in case of HTML.

孤千羽 2024-09-14 21:07:55

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

$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) . '...';
}

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) . '...';
}
冷默言语 2024-09-14 21:07:55

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

例如:
我们需要将“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;
    }

}

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.

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

}
·深蓝 2024-09-14 21:07:54

自 PHP 4.0.6 版本起,此功能已内置到 PHP 中。 查看文档

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

// outputs Hello W...

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

This functionality has been built into PHP since version 4.0.6. See the docs.

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

// outputs Hello W...

Note that the trimmarker (the ellipsis above) are included in the truncated length.

暖伴 2024-09-14 21:07:53
//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;
}
//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 '...'

Update 2:

Or as function:

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

Update 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:

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文