Multi-byte safe wordwrap() function for UTF-8

前端 未结 9 1008
太阳男子
太阳男子 2020-12-01 13:17

PHP\'s wordwrap() function doesn\'t work correctly for multi-byte strings like UTF-8.

There are a few examples of mb safe functions in the comments, but with some di

9条回答
  •  旧时难觅i
    2020-12-01 13:20

    This one seems to work well...

    function mb_wordwrap($str, $width = 75, $break = "\n", $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);
    }
    

提交回复
热议问题