while ($i
$star .= '*';
$i++;
}
return substr_replace($str, $star, $start, $count);
}
复制代码
不擅长算法,这里就用很普通的逻辑来展示啦,没有用到啥数学公式。
1、if($start >= 0)这里做start大于等于0与小于0的分支
2、在start 的分之中,分别再做length 大于0,小于0和等于0的三个分支
3、最后计算出start、count和要替换的星号字符串,最后计算出的start与count都是正数,运用substr_replace做替换
四、单元测试
复制代码
public function testReplaceStar()
{
$actual = App_Util_String::replaceStar('123456789', 3, 2);
$this->assertEquals($actual, '123**6789');
$actual = App_Util_String::replaceStar('123456789', 9);
$this->assertEquals($actual, '123456789');
$actual = App_Util_String::replaceStar('123456789', 9, 2);
$this->assertEquals($actual, '123456789');
$actual = App_Util_String::replaceStar('123456789', 9, -9);
$this->assertEquals($actual, '*********');
$actual = App_Util_String::replaceStar('123456789', 9, -10);
$this->assertEquals($actual, '*********');
$actual = App_Util_String::replaceStar('123456789', 9, -11);
$this->assertEquals($actual, '*********');
$actual = App_Util_String::replaceStar('123456789', 3);
$this->assertEquals($actual, '123******');
$actual = App_Util_String::replaceStar('123456789', 0);
$this->assertEquals($actual, '*********');
$actual = App_Util_String::replaceStar('123456789', 0, 2);
$this->assertEquals($actual, '**3456789');
$actual = App_Util_String::replaceStar('123456789', 3, -3);
$this->assertEquals($actual, '1***56789');
$actual = App_Util_String::replaceStar('123456789', 1, -5);
$this->assertEquals($actual, '**3456789');
$actual = App_Util_String::replaceStar('123456789', 3, -3);
$this->assertEquals($actual, '1***56789');
$actual = App_Util_String::replaceStar('123456789', -3, 2);
$this->assertEquals($actual, '123456**9');
$actual = App_Util_String::replaceStar('123456789', -3, 5);
$this->assertEquals($actual, '123456***');
$actual = App_Util_String::replaceStar('123456789', -1, 2);
$this->assertEquals($actual, '12345678*');
$actual = App_Util_String::replaceStar('123456789', -1, -2);
$this->assertEquals($actual, '1234567**');
$actual = App_Util_String::replaceStar('123456789', -4, -7);
$this->assertEquals($actual, '******789');
$actual = App_Util_String::replaceStar('123456789', -1, -3);
$this->assertEquals($actual, '123456***');
$actual = App_Util_String::replaceStar('123456789', -1);
$this->assertEquals($actual, '*********');
$actual = App_Util_String::replaceStar('123456789', -2);
$this->assertEquals($actual, '********9');
$actual = App_Util_String::replaceStar('123456789', -9);
$this->assertEquals($actual, '*23456789');
$actual = App_Util_String::replaceStar('123456789', -10);
$this->assertEquals($actual, '123456789');
$actual = App_Util_String::replaceStar('123456789', -10, -2);
$this->assertEquals($actual, '123456789');
}
http://www.bkjia.com/PHPjc/871181.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/871181.htmlTechArticlePHP将部分内容替换成星号 在最近的项目中,会碰到到某人的手机号码隐藏中间几位,身份证号码只显示末尾4位的需求。当时一开始是网上...