亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在PHP的前20個單詞中截斷字符串?

如何在PHP的前20個單詞中截斷字符串?

PHP
白衣非少年 2019-09-21 13:43:23
如何在PHP中20個單詞后截斷字符串?
查看完整描述

3 回答

?
慕尼黑8549860

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


查看完整回答
反對 回復 2019-09-21
?
慕妹3146593

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(""));  # => ""


查看完整回答
反對 回復 2019-09-21
  • 3 回答
  • 0 關注
  • 456 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號