本文介紹了UTF-8 的多字節安全 wordwrap() 函數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
PHP 的 wordwrap()
函數對于多像UTF-8這樣的字節串.
PHP's wordwrap()
function doesn't work correctly for multi-byte strings like UTF-8.
評論里有幾個mb安全函數的例子,但是有了一些不同的測試數據,它們似乎都有一些問題.
There are a few examples of mb safe functions in the comments, but with some different test data they all seem to have some problems.
該函數應采用與 wordwrap()
完全相同的參數.
The function should take the exact same parameters as wordwrap()
.
特別要確保它適用于:
- 如果
$cut = true
,則剪切中間詞,否則不剪切中間詞 - 如果
$break = ' '
,不要在單詞中插入額外的空格 - 也適用于
$break = " "
- 適用于 ASCII 和所有有效的 UTF-8
- cut mid-word if
$cut = true
, don't cut mid-word otherwise - not insert extra spaces in words if
$break = ' '
- also work for
$break = " "
- work for ASCII, and all valid UTF-8
推薦答案
這個好像很好用...
function mb_wordwrap($str, $width = 75, $break = "
", $cut = false, $charset = null) {
if ($charset === null) $charset = mb_internal_encoding();
$pieces = explode($break, $str);
$result = array();
foreach ($pieces as $piece) {
$current = $piece;
while ($cut && mb_strlen($current) > $width) {
$result[] = mb_substr($current, 0, $width, $charset);
$current = mb_substr($current, $width, 2048, $charset);
}
$result[] = $current;
}
return implode($break, $result);
}
這篇關于UTF-8 的多字節安全 wordwrap() 函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!