php:怎樣將中文字元以規定字元長度分段截取並將每段放入數組元素中解決方案

來源:互聯網
上載者:User
php:怎樣將中文字元以規定字元長度分段截取並將每段放入數組元素中
如:
$cont = "關於烹飪. 這套廚師類的魔幻小說其實小三已經醞釀很長時間了,但一直都覺得不成熟,就沒有下筆.空速即……";
function subpart($cont,10,"utf8"){……}
$array = subpart($cont,10,"utf8");

$array = ([0]=>"關於烹飪. ",[1]=>"這套廚師類",[2]=>"的魔幻小說",……);

請教,subpart()函數應該怎樣寫?

------解決方案--------------------
function subpart($cont,$l,$utf)
{
$len = mb_strlen($cont, $utf);
for($i; $i<$len; $i+=$l)
$arr[] = mb_substr($cont, $i, $l, $utf);
Return $arr;
}
$cont = '中國人民,中國人民銀行';
print_r(subpart($cont, 5, "utf8"));
------解決方案--------------------
$cont = "關於烹飪. 這套廚師類的魔幻小說其實小三已經醞釀很長時間了,但一直都覺得不成熟,就沒有下筆.空速即……";

$array = subpart($cont,10,"utf8");

echo '
';
print_r($array);

function subpart($cont, $len, $charset)
{
$contlen = strlen($cont);

for ($i=0; $i<=$contlen;$i+=$len)
{
$contarr[] = substr($cont,$i,$len);
}
return $contarr;
}
?>
------解決方案--------------------
樓上的方法都正確,當然你也可以寫Regex匹配要分割的字元,比如‘,’‘|’。
然後用substr裝數組
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.