一尘不染

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

php

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


阅读 224

收藏
2020-05-26

共1个答案

一尘不染

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 ...
2020-05-26