php - 如何将字符串截断为 PHP 中的前 20 个单词?

标签 php string

如何在 PHP 中截断 20 个单词后的字符串?

最佳答案

function limit_text($text, $limit) {
    if (str_word_count($text, 0) > $limit) {
        $words = str_word_count($text, 2);
        $pos   = array_keys($words);
        $text  = substr($text, 0, $pos[$limit]) . '...';
    }
    return $text;
}

echo limit_text('Hello here is a long sentence that will be truncated by the', 5);

输出:

Hello here is a long ...

关于php - 如何将字符串截断为 PHP 中的前 20 个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/965235/

相关文章:

C访问冲突写入位置scanf_s

javascript - 如何使用php在下拉列表中自动更新三天的日期

string - 零前的Datasnap字符串参数被修剪为零

php - 如何替换该字符串中的斜杠?

php - CakePHP 3 - 通过其他表连接?

c# - 如何在 .NET Core 中查找字体和字符串指标?

c - Strptime开源代码未实现

java - 根据字符串更改Textview

php - 获取后运行编码 json 时出错

php - 获取实例的静态属性