php - 将字符串限制为 PHP 中的前 5 个单词或前 42 个字符

标签 php string

如果我在 PHP 中有一个字符串,它在 PHP 中是令人讨厌的长字符串,我想缩短它然后向其附加一些内容。

我想将它缩短到前 6 个单词或 42 个字符,无论哪个更短,然后在它被缩短的情况下附加一个“...”。

唯一不会缩短并且不添加“...”的情况是它最初少于 6 个单词或 42 个字符。

我如何在 PHP 中执行此操作?

从逻辑上讲,我认为我会用空格拆分字符串,然后将每个内容添加到数组中的空格之前,只从该数组中取出前 6 个元素并将它们写入新字符串。

这是我目前的代码:

str_1 = 'The quick brown fox jumped over the lazy dog';
$words = explode(" ", $str_1);
$counter = 0;
str_2 = '';
foreach($words as $word){
    if($counter < 5){
        //append $words[counter] to str_2;
        counter++;
    }
    else{
        break;
    }
}

我不知道如何进行字符计数、比较或追加。

有没有人有什么想法?

最佳答案

我做的这个函数看起来很整洁:

function truncate($input, $maxWords, $maxChars)
{
    $words = preg_split('/\s+/', $input);
    $words = array_slice($words, 0, $maxWords);
    $words = array_reverse($words);

    $chars = 0;
    $truncated = array();

    while(count($words) > 0)
    {
        $fragment = trim(array_pop($words));
        $chars += strlen($fragment);

        if($chars > $maxChars) break;

        $truncated[] = $fragment;
    }

    $result = implode($truncated, ' ');

    if ($input == $result)
    {
        return $input;
    }
    else
    {
        return preg_replace('/[^\w]$/', '', $result) . '...';
    }
}

一些测试:

$str = 'The quick brown fox jumped over the lazy dog';

echo truncate($str, 5, 42); // The quick brown fox jumped...
echo truncate($str, 3, 42); // The quick brown...
echo truncate($str, 50, 30); // The quick brown fox jumped over the...
echo truncate($str, 50, 100); // The quick brown fox jumped over the lazy dog

它也不会将单词减半,因此如果一个单词将字符数推到超过提供的限制,它将被忽略。

关于php - 将字符串限制为 PHP 中的前 5 个单词或前 42 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16725974/

相关文章:

javascript - 使用larragon和Vue,组件不渲染

javascript - php语法有问题吗?

c - 我的 C 程序在不应该打印的时候打印了两个不同的内容

objective-c - 获取 Apple 事件的可用描述

c++ - 绳索数据结构

php - 一段时间后自动解封用户

php - 什么情况下我们不应该在 javascript 中使用 php?

python - Python 中的子字符串搜索

php - 将最后一个 id 插入的变量发送到 php 中的另一个页面

c++ - 用 ASCII 等效字符替换字符串中的所有非 ASCII 字符