Home  >  Article  >  Backend Development  >  PHP calculate string length

PHP calculate string length

巴扎黑
巴扎黑Original
2016-11-22 10:36:241278browse

/**
* Calculate the length of the string (Chinese characters are calculated as two characters)
*
* @param string $str String
*
* @return int
*/
function myStrLen($str){
    $length = strlen(preg_replace('/[x00-x7F]/', '', $str));

    if ($length){
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else{
        return strlen($str);
    }
}

/**
* Calculate the length of the string (Chinese characters are calculated as one character)
*
* @param string $str String
*
* @return int
*/
function cnForOneBetLen($str){
    $length = strlen(preg_replace('/[x00-x7F]/', '', $str));

    if ($length){
        return strlen($str) - $length + intval($length / 3) * 1;
    }
    else{
        return strlen($str);
    }
}


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