PHP mb_wordwrap 中文折行

180it 2020-03-05 PM 3104℃ 0条
function mb_wordwrap($str, $width = 75, $break = "\n", $cut = false) {
      $lines = explode($break, $str);
        foreach ($lines as &$line) {
            $line = rtrim($line);
            if (mb_strlen($line) <= $width)
                continue;
            $words = explode(' ', $line);
            $line = '';
            $actual = '';
            foreach ($words as $word) {
                if (mb_strlen($actual.$word) <= $width)
                    $actual .= $word.' ';
                else {
                    if ($actual != '')
                        $line .= rtrim($actual).$break;
                    $actual = $word;
                    if ($cut) {
                        while (mb_strlen($actual) > $width) {
                            $line .= mb_substr($actual, 0, $width).$break;
                            $actual = mb_substr($actual, $width);
                        }
                    }
                    $actual .= ' ';
                }
            }
            $line .= trim($actual);
        }
        return implode($break, $lines);
    }

<?php
//支持中文
$str = "An example of a long word is: Supercalifragulistic";
echo mb_wordwrap($str,15,"
\n",TRUE);
?>

<?php
//不支持中文
$str = "An example of a long word is: Supercalifragulistic";
echo wordwrap($str,15,"
\n",TRUE);
?>

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP mb_wordwrap 中文折行