PHP中文字符串替换其中为*的方法

  •   
  • 9949
  • PHP
  • 2
  • super_dodo
  • 2014/06/18

在项目中需要对字符串的部分进行隐藏或者替换。譬如手机号码的中间几位进行隐藏,中文名字的中间替换为*号等。

英文和数字等可直接用php的自带的函数进行处理。但是中文因为编码的缘故会出现不一样的效果。需要自己定义方法进行处理。此处针对大多数UTF-8的用户。

//英文和数字等
substr_replace() 函数把字符串的一部分替换为另一个字符串。
substr_replace(string,replacement,start,length);
echo substr_repalce('18687494999','****',3,4);//得到186****4999

//对于UTF-8的中文
//使用该方法可以替换中文字符串的内容--使用方法类似于substr_replace_cn
//在utf-8下一个汉字占三个字节
//$repalce 为要替换成的字符串 start为开始的字符位置默认0开始 len为替换的长度
public function substr_replace_cn($string, $repalce = '*',$start = 0,$len = 0) {
$count = mb_strlen($string, 'UTF-8'); //此处传入编码,建议使用utf-8。此处编码要与下面mb_substr()所使用的一致
if(!$count) { return $string; }
if($len == 0){
$end = $count; //传入0则替换到最后
}else{
$end = $start + $len; //传入指定长度则为开始长度+指定长度
}
$i = 0;
$returnString = '';
while ($i < $count) { //循环该字符串 $tmpString = mb_substr($string, $i, 1, 'UTF-8'); // 与mb_strlen编码一致 if ($start <= $i && $i < $end) { $returnString .= $repalce; } else { $returnString .= $tmpString; } $i ++; } return $returnString; } //使用正则表达式---视情况而定 preg_replace()//执行正则表达式的搜索和替换 preg_replace($pattern, $replacement, $string); [/php]

No matter how your heart is grieving, if you keep on believing, the dreams that you wish will come true.

不管心有多痛,若坚信不移,梦想总会成真。