3 回答

TA貢獻1818條經驗 獲得超11個贊
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 ...

TA貢獻1820條經驗 獲得超9個贊
將數字更改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("")); # => ""
- 3 回答
- 0 關注
- 456 瀏覽
添加回答
舉報