wordwrapのマルチバイト対応版です。
文字のバイト数ではなく、文字の幅・文字の長さで文字を追加する様にしています。
半角だと「1」全角だと「2」の幅でカウントされます。
wordwrapは、一定の文字数目に
関数
[sourcecode language=”php”]
function mb_wordwrap( $str, $width=50, $break="\n" ){
$w = mb_strwidth( $str , "eucJP-win" );
$arr = array();
if( $w < $width ){
return $str;
}
while( $w > $width ){
$trimStr = mb_strimwidth( $str , 0, $width , "" , "eucJP-win" );
$arr[] = $trimStr;
$str = preg_replace( "/^$trimStr/", "" , $str );
$w = mb_strwidth( $str , "eucJP-win" );
}
$arr[] = $str;
return implode( $break, $arr );
}
[/sourcecode]
テスト
こんな感じで結果が出力されます。
[sourcecode language=”php”]
$str = "あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほ";
echo mb_wordwrap( $str, 50, "<br />" );
[/sourcecode]
[sourcecode language=”bash”]
あいうえおかきくけこさしすせそたちつてとなにぬねの
はひふへほ
[/sourcecode]
コメント