For example, the Smarty template uses the string truncation function modifier. truncate. php. this truncate function can intercept English strings, which are commonly used. After all, Smarty is developed by foreigners. if it is used directly to intercept Chinese characters, you will be waiting for garbled characters. In addition, the length values written during truncation are subject to letters, that is, the length of a Chinese character is 2 (GB
For example, the Smarty template uses the string truncation function modifier. truncate. php. this truncate function can intercept English strings, which are commonly used. After all, Smarty is developed by foreigners. if it is used directly to intercept Chinese characters, you will be waiting for garbled characters. Also, the length value written during the truncation is based on letters, that is, the length of a Chinese character is 2 (GBK) or 3 (UTF-8) bytes. Therefore, the following plug-ins can be used for Chinese characters.
This screenshot function comes from the string class in ThinkPHP and is quite useful. What we need to do is to make this function a Smarty plug-in for direct use in the template. OK.
Open the Smartyplugins folder, which is a default plug-in. Here we can see this modifier. truncate. php. Next, we will create a php file in this directory to intercept Chinese strings. If the function name is used, use the default value in TP. Create the file modifier. msubstr. php. the code is as follows:
- /**
- * Smarty Chinese string truncation
- * Tianya PHP blog Co., http://blog.phpha.com.
- */
- Function smarty_modifier_msubstr ($ str, $ start = 0, $ length, $ charset = "UTF-8", $ suffix = true ){
- If (function_exists ("mb_substr ")){
- Return mb_substr ($ str, $ start, $ length, $ charset );
- } Elseif (function_exists ('iconv _ substr ')){
- Return iconv_substr ($ str, $ start, $ length, $ charset );
- }
- $ Re ['utf-8'] = "/[x01-x7f] | [xc2-xdf] [x80-xbf] | [xe0-xef] [x80-xbf] {2} | [xf0-xff] [x80-xbf] {3 }/";
- $ Re ['gb2312'] = "/[x01-x7f] | [xb0-xf7] [xa0-xfe]/";
- $ Re ['gbk'] = "/[x01-x7f] | [x81-xfe] [x40-xfe]/";
- $ Re ['big5'] = "/[x01-x7f] | [x81-xfe] ([x40-x7e] | xa1-xfe])/";
- Preg_match_all ($ re [$ charset], $ str, $ match );
- $ Slice = join ("", array_slice ($ match [0], $ start, $ length ));
- If ($ suffix) return $ slice .'...';
- Return $ slice;
- }
- ?>
The following describes the use of the template. For example, if you want to extract the length of the homepage news title, the variable name is title, as follows:
- <{$title|msubstr:0:5}>
It indicates that, starting from the first character, the truncation length is 5, that is, 5 Chinese characters. Here, this function is processed. a letter has the same length as a Chinese character and is 1.
- $ Title = 'Welcome to the blog of Tianya ';
- // The result is "Welcome to Heaven"
- $ Title = 'tianya PHP blog ';
- // The result is "Tianya PHP"