获取字符串的前n个字符

PHP字符串裁剪技巧

本文翻译自:Get first n characters of a string

How can I get the first n characters of a string in PHP? 如何在PHP中获取字符串的前n个字符? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed? 将字符串修剪为特定字符数的最快方法是什么,如果需要,可以附加“...”?


#1楼

参考:https://stackoom.com/question/DGX2/获取字符串的前n个字符


#2楼

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) ; 例如: str_short("hahahahahah",5) ;
it will cut of your string and add "..." at the end 它将剪切你的字符串并在最后添加“...”
:) :)


#3楼

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表示操作字符串。


#4楼

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楼

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

#6楼

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,此方法将删除所有标记。

### 3.1 获取字符串N个字符的性能表现 在 C# 中,获取字符串 N 个字符通常使用 `Substring` 方法。由于字符串是不可变对象,每次调用 `Substring` 都会创建一个新的字符串实例,这意味着需要进行内存分配和字符复制操作[^1]。 #### 3.1.1 时间与空间复杂度 `Substring` 方法的时间复杂度为 O(n),其中 n 是截取的字符数量。该操作需要复制原始字符串中的字符到新分配的内存空间中,因此其性能开销与截取长度成正比。空间复杂度同样为 O(n),因为新字符串将占用与截取长度相当的内存空间[^4]。 例如: ```csharp string original = "This is a long string."; string firstN = original.Substring(0, 10); // 获取10个字符 ``` 此操作在小规模数据处理中性能良好,但如果在高频率调用或大规模数据处理中频繁使用,可能会显著影响性能。 #### 3.1.2 内存与垃圾回收影响 由于每次调用 `Substring` 都会生成新的字符串对象,频繁使用该方法会导致堆内存中产生大量短生命周期的对象,从而增加垃圾回收(GC)的频率和压力。这在高并发或性能敏感的应用场景中尤为明显[^2]。 #### 3.1.3 替代方案与优化建议 为了减少内存分配和提升性能,可以考虑以下方式: - 使用 `Span<char>` 或 `ReadOnlySpan<char>`(.NET Core 2.1 及以上)进行无分配的字符串操作: ```csharp ReadOnlySpan<char> span = original.AsSpan(); ReadOnlySpan<char> firstNChars = span.Slice(0, 10); ``` - 对于需要多次截取相同长度的字符串,可以缓存结果以避免重复计算。 - 在字符串处理密集型场景中,结合 `ArrayPool<char>` 或 `MemoryPool<char>` 实现手动内存管理,以减少 GC 压力。 --- ### 3.2 实际性能考量 在日志系统、界面显示或数据预处理等实际应用中,获取字符串 N 个字符的需求较为常见。例如在日志记录中限制每条日志的显示长度,或在 UI 中展示文本摘要。此时,应根据调用频率、字符串长度和系统资源使用情况评估是否需要采用更高效的字符串操作方式[^3]。 --- ### 3.3 总结 获取字符串 N 个字符在 C# 中通常通过 `Substring` 实现,其性能表现良好,但受限于字符串的不可变性,频繁使用会导致内存分配和垃圾回收压力增加。结合 `Span<char>`、内存池等技术可以有效优化性能,尤其适用于高并发或资源敏感的场景。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值