note 128386 added to function.mb-strimwidth

From: Date: Wed, 12 Apr 2023 13:54:05 +0000
Subject: note 128386 added to function.mb-strimwidth
Groups: php.notes 
Request: Send a blank email to php-notes+get-220342@lists.php.net to get a copy of this message
I see a lot of usage in the field where people rely on this function to truncate a string to a given length and append some chars at the end following example #1 in the above documentation. While this works just fine with Western alphabets, it should be noted that a string's width is NOT necessarily the same as its length. In Chinese, Japanese and Korean, some characters can be represented as full or half width, which may lead to unexpected results... <?php $str = ['English' => 'Switzerland', 'Half width' => 'スイス', 'Full width' => 'スイス', ]; foreach ($str as $w => $s) { printf("%-10s: %s (bytes=%d chars=%d width=%d)\nSubstring : %s\nTrim width: %s\n\n", $w, $s, strlen($s), mb_strlen($s), mb_strwidth($s), mb_substr($s, 0, 3), mb_strimwidth($s, 0, 3) ); } /* Output # With ASCII, chars == width, so everything works as expected English : Switzerland (bytes=11 chars=11 width=11) Substring : Swi Trim width: Swi # With half-width katakanas, it works too Half width: スイス (bytes=9 chars=3 width=3) Substring : スイス Trim width: スイス # Full-width katakanas are twice as wide, so we only get the 1st 'su' ! Full width: スイス (bytes=9 chars=3 width=6) Substring : スイス Trim width: ス */ >? ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.13.130 (proxied: 193.134.187.35) ---- Manual Page -- https://php.net/manual/en/function.mb-strimwidth.php Edit -- https://main.php.net/note/edit/128386 Del: integrated -- https://main.php.net/note/delete/128386/integrated Del: useless -- https://main.php.net/note/delete/128386/useless Del: bad code -- https://main.php.net/note/delete/128386/bad+code Del: spam -- https://main.php.net/note/delete/128386/spam Del: non-english -- https://main.php.net/note/delete/128386/non-english Del: in docs -- https://main.php.net/note/delete/128386/in+docs Del: other reasons-- https://main.php.net/note/delete/128386 Reject -- https://main.php.net/note/reject/128386 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220342) next »