--- fenglin/lib/str_process.inc.php 2004/12/10 15:54:32 1.5 +++ fenglin/lib/str_process.inc.php 2025/07/02 02:00:57 1.20 @@ -1,75 +1,127 @@ -127) - { - $hz_ok = (!$hz_ok); - } - if (ord($str[$i])<=127) + $c = $str[$i]; + + // Process UTF-8 Chinese characters + $v1 = ord($c); + if ($v1 & 0b10000000) //head of multi-byte character { - $hz_ok = true; + $v2 = ($v1 & 0b01110000) << 1; + while ($v2 & 0b10000000) + { + $i++; + $c .= $str[$i]; + $v2 = ($v2 & 0b01111111) << 1; + } + + $ret += 2; } - if ($line_count >= $width && $hz_ok) + else { - $lines[$lines_count++] = $line; - $line = $prefix; - $line_count = strlen($line); + $ret++; } } - $lines[$lines_count++] = $line; - $result = ""; - for($i=0;$i<$lines_count;$i++) - { - $result.=($lines[$i]."\r\n"); - } - return $result; + return $ret; } -function str_process($str,$prefix="",$width=75) +function split_line(string $str, string $prefix = "", int $width = 76, int $lines_limit = PHP_INT_MAX, string $end_of_line = "\n") : string { + if ($width <= 0) + { + return $str; + } + $result = ""; - - $lines = explode("\n",str_replace("\r\n","\n",$str)); + $len = strlen($str); + $prefix_len = str_length($prefix); - foreach($lines as $line) + $lines_count = 0; + + $line = $prefix; + $line_len = $prefix_len; + for ($i = 0; $i < $len && $lines_count < $lines_limit; $i++) { - $result .= split_line($line,$prefix,$width); + $c = $str[$i]; + + // Skip special characters + if ($c == "\r" || $c == "\7") + { + continue; + } + + if ($c == "\n") + { + if ($lines_count + 1 >= $lines_limit) + { + break; + } + + $result .= ($line . $end_of_line); + $lines_count++; + $line = $prefix; + $line_len = $prefix_len; + continue; + } + + // Process UTF-8 Chinese characters + $v1 = ord($c); + if ($v1 & 0b10000000) //head of multi-byte character + { + $v2 = ($v1 & 0b01110000) << 1; + while ($v2 & 0b10000000) + { + $i++; + $c .= $str[$i]; + $v2 = ($v2 & 0b01111111) << 1; + } + + // Each UTF-8 CJK character should use two character length for display + if ($line_len + 2 > $width) + { + if ($lines_count + 1 >= $lines_limit) + { + break; + } + + $result .= ($line . $end_of_line); + $lines_count++; + $line = $prefix; + $line_len = $prefix_len; + } + $line_len += 2; + } + else + { + $line_len++; + } + + if ($line_len > $width) + { + if ($lines_count + 1 >= $lines_limit) + { + break; + } + + $result .= ($line . $end_of_line); + $lines_count++; + $line = $prefix; + $line_len = $prefix_len + 1; + } + + $line .= $c; } - - return $result; -} -function str_b_lines($str,$max_line=1) -{ - $result = ""; - $l = 0; - $lines = explode("\n",str_replace("\r\n","\n",$str)); - foreach($lines as $line) + if ($lines_count < $lines_limit) { - $result .= ($line."\r\n"); - $l += (strlen($line)/256 + 1); - if ($l >= $max_line) - break; + $result .= $line; } return $result; } - -?>