Skip to content

Commit 110a8e7

Browse files
committed
implement strWidth() for CJK users
strWidth($str) returns the width of string str, where halfwidth characters count as 1, and fullwidth characters count as 2.
1 parent c0e4238 commit 110a8e7

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

action/editor.php

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ public function build_table($data, $meta)
154154
// find maximum column widths
155155
for ($row = 0; $row < $rows; $row++) {
156156
for ($col = 0; $col < $cols; $col++) {
157-
$len = Utf8\PhpString::strlen($data[$row][$col]);
157+
$len = $this->strWidth($data[$row][$col]);
158158

159159
// alignment adds padding
160160
if ($meta[$row][$col]['align'] == 'center') {
@@ -195,7 +195,7 @@ public function build_table($data, $meta)
195195
}
196196

197197
// copy colspans to rowspans below if any
198-
if ($meta[$row][$col]['colspan'] > 1){
198+
if ($meta[$row][$col]['colspan'] > 1) {
199199
for ($i = 1; $i < $meta[$row][$col]['rowspan']; $i++) {
200200
$meta[$row + $i][$col]['colspan'] = $meta[$row][$col]['colspan'];
201201
}
@@ -232,4 +232,31 @@ public function build_table($data, $meta)
232232
return $table;
233233
}
234234

235+
/**
236+
* Return width of string
237+
*
238+
* @param string $str
239+
* @return int
240+
*/
241+
public function strWidth($str)
242+
{
243+
static $callable;
244+
245+
if (isset($callable)) {
246+
return $callable($str);
247+
} else {
248+
if (UTF8_MBSTRING) {
249+
// count fullwidth characters as 2, halfwidth characters as 1
250+
$callable = 'mb_strwidth';
251+
} elseif (method_exists(Utf8\PhpString::class, 'strlen')) {
252+
// count any characters as 1
253+
$callable = [Utf8\PhpString::class, 'strlen'];
254+
} else {
255+
// fallback deprecated utf8_strlen since 2019-06-09
256+
$callable = 'utf8_strlen';
257+
}
258+
return $this->strWidth($str);
259+
}
260+
}
261+
235262
}

0 commit comments

Comments
 (0)