如何在PHP的前20个单词中截断字符串? [英] How can I truncate a string to the first 20 words in PHP?

查看:58
本文介绍了如何在PHP的前20个单词中截断字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I truncate a string after 20 words in PHP?

推荐答案

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 blah blah blah blah blah hahahaha haha haaaaaa', 5);

输出:

Hello here is a long ...

这篇关于如何在PHP的前20个单词中截断字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆