For the beauty of the front end, I use the Smarty built-in truncate function for character length control, such as the title of some articles is too long, and in fact it is not necessary to fully display. Truncate can be intercepted, for example:
The code is as follows |
Copy Code |
{$articleTitle |truncate:11: "...": true} |
But if the title is Chinese, then it is very easy to appear garbled! This is because Smarty's truncate intercepts the characters (taking up a byte), but if it is Chinese, such as UTF-8 (3 bytes), then the argument 11 here is the byte number, and if it is Chinese, it actually intercepts 3 characters (9 bytes). The remaining 2 bytes can not represent a Chinese character, then it will be in the form of garbled display!
Finding a solution from the Internet is good:
The code is as follows |
Copy Code |
<?php function Smarty_modifier_truncate_utf ($string, $length =, $etc = ' ... ') { $result = '; $string = Html_entity_decode (Trim (strip_tags ($string)), ent_quotes, ' utf-8 '); for ($i = 0, $j = 0; $i < strlen ($string); $i + +) { if ($j >= $length) { for ($x = 0, $y = 0; $x < strlen ($etc); $x + +) { if ($number = Strpos (Str_pad (Decbin (Ord (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left), ' 0 ') { $x + + $number-1; $y + +; } Else { $y + 0.5; } } $length-= $y; Break } if ($number = Strpos (Str_pad (Decbin (Ord (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left), ' 0 ') { $i + + $number-1; $j + +; } Else { $j + 0.5; } } for ($i = 0; ($i < strlen ($string)) && ($length > 0)); $i + +) { if ($number = Strpos (Str_pad (Decbin (Ord (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left), ' 0 ') { if ($length < 1.0) { Break } $result. = substr ($string, $i, $number); $length-= 1.0; $i + + $number-1; } Else { $result. = substr ($string, $i, 1); $length-= 0.5; } } $result = Htmlentities ($result, ent_quotes, ' utf-8 '); if ($i < strlen ($string)) { $result. = $etc; } return $result; } ?> |
In fact, the principle is very simple, that is, every time from the string out of a character (including English letters, symbols, Chinese characters, etc.), and then turn it into ASCII, as for why to convert to ASCII, because each character corresponds to the only one ASCII code, and its distribution is still regular, For example, the ASCII code of any one Chinese character is greater than 255. This allows us to process the characters, if the current characters are English letters or printable symbols (ASCII values from 0~254), then intercept length +1, if the current character is Chinese (ASCII value >255), then the Intercept length is +3 (UTF-8). So after the end of the loop will know the actual need to intercept the number of bytes!
Forget to say, write the above function to modifier.truncate_utf.php this file, and then put it in the Smarty plugins directory, when called:
The code is as follows |
Copy Code |
<{$topic |truncate_utf:11: "..."}> |