猿问

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

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



白衣非少年
浏览 430回答 3
3回答

慕尼黑8549860

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 ...

慕妹3146593

将数字更改3为以下数字20可获得前20个字,或将其作为参数传递。下面演示了如何获取前3个字:(因此将更3改为20可以更改默认值):function first3words($s, $limit=3) {    return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);   }var_dump(first3words("hello yes, world wah ha ha"));  # => "hello yes, world"var_dump(first3words("hello yes,world wah ha ha"));   # => "hello yes,world"var_dump(first3words("hello yes world wah ha ha"));   # => "hello yes world"var_dump(first3words("hello yes world"));  # => "hello yes world"var_dump(first3words("hello yes world.")); # => "hello yes world"var_dump(first3words("hello yes"));  # => "hello yes"var_dump(first3words("hello"));  # => "hello"var_dump(first3words("a")); # => "a"var_dump(first3words(""));  # => ""
随时随地看视频慕课网APP
我要回答