替换字符串中间部分为*

/**
* 使用$replace替换字符串的中间部分
*/
function replaceCenterWithChar($str, $replace = "*", $leftLen = 2, $rightLen = 2, $replaceLen = 3) {
        $length = mb_strlen($str, "utf-8");
        if ($length <= 1) {
            return $str;
        } elseif ($length == 2) {
            return mb_substr($str, 0, 1, "utf-8").str_repeat($replace, $replaceLen).mb_substr($str, 1, 1, "utf-8");
        } elseif ($length < $leftLen) {
            return $str;
        } elseif ($length == $leftLen) {
            return mb_substr($str, 0, $leftLen - 1, "utf-8").str_repeat($replace, $replaceLen).mb_substr($str, $length - 1, 1, "utf-8");
        } elseif ($length < ($leftLen+$rightLen)) {
            return mb_substr($str, 0, $leftLen, "utf-8").str_repeat($replace, $replaceLen).mb_substr($str, $leftLen, $length - $leftLen, "utf-8");
        } elseif ($length > $rightLen) {
            return mb_substr($str, 0, $leftLen, "utf-8").str_repeat($replace, $replaceLen).mb_substr($str, $length - $rightLen, $rightLen,  "utf-8");
        } else {
            return mb_substr($str, 0, $leftLen, "utf-8").str_repeat($replace, $replaceLen).mb_substr($str, $length - $leftLen, $rightLen,  "utf-8");
        }
    }

转载于:https://my.oschina.net/u/3132973/blog/809670

你可能感兴趣的:(替换字符串中间部分为*)