PHP实现姓名和手机号星号*替换

实现mb_substr_replace

   function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
    {
        if (extension_loaded('mbstring') === true) {
            $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);

            if ($start < 0) {
                $start = max(0, $string_length + $start);
            } else if ($start > $string_length) {
                $start = $string_length;
            }

            if ($length < 0) {
                $length = max(0, $string_length - $start + $length);
            } else if ((is_null($length) === true) || ($length > $string_length)) {
                $length = $string_length;
            }

            if (($start + $length) > $string_length) {
                $length = $string_length - $start;
            }

            if (is_null($encoding) === true) {
                return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
            }

            return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
        }

        return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
    }

用户名星号替换

替换样例:

  • 马克思:马*思
  • 马思:*思
  • 马列主义:马*义
    public function getMaskName()
    {
        if (mb_strlen($this->name) > 2) {
            return mb_substr_replace($this->name, '*', 1, -1);
        } else {
            return mb_substr_replace($this->name, '*', 0, -1);
        }
    }

手机号星号替换

替换样例:

  • 12345679878:123***878
    public function getMaskMobile()
    {
        return substr_replace($this->mobile, '***', 3, -3);
    }

发表评论