Home >Backend Development >PHP Tutorial >PHP interception of Chinese and English string operations
I encountered such a problem today. I believe everyone has encountered it. Due to typesetting requirements, if the user name is too long, it will be intercepted and displayed as... . Our needs are similar to Sina Weibo. If it is Chinese, it can display up to 5 digits. If it exceeds 5 digits, it will display 4 Chinese characters, three... As we all know, one Chinese character occupies two English positions during typesetting. Therefore, a maximum of 10 digits must be displayed, analogous to the above.
The solution found on the Internet is not very good, so I wrote one myself. I put them in the helper. Let’s not talk about the ideas, let’s go directly to the code.
<?php class Zend_View_Helper_UserName { public function userName($userName, $length) { $retUserName = ''; $position = 0; $count = 1; while ($count <= $length) { $subStr = mb_substr($userName, $position, 1, 'UTF-8'); if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $subStr)) { $count += 2; } else { $count++; } $position++; $retUserName .= $subStr; } $retUserNameLength = mb_strlen($retUserName); $userNameLength = mb_strlen($userName) ; if ($retUserNameLength >= $userNameLength - 1 && $retUserNameLength <= $userNameLength) { $retUserName = $userName; } else { $retUserName .= '...'; } return $retUserName; } }
When used in this way, you can easily intercept the name. And it’s suitable for both Chinese and English. The disadvantage is that it may consume some resources than functions such as substr.