Home  >  Article  >  Backend Development  >  PHP interception of Chinese and English string operations

PHP interception of Chinese and English string operations

巴扎黑
巴扎黑Original
2016-11-22 10:43:081133browse

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 = &#39;&#39;;
        $position = 0;
        $count = 1;
        while ($count <= $length) {
            $subStr = mb_substr($userName, $position, 1, &#39;UTF-8&#39;);
            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 .= &#39;...&#39;;
        }
        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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php error reportNext article:php error report