Home >Backend Development >PHP Tutorial >PHP string replacement with asterisks or other characters (mobile phone number, ID card)_PHP tutorial

PHP string replacement with asterisks or other characters (mobile phone number, ID card)_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:44:032450browse

In PHP, the character at the specified position in the string is replaced with an asterisk. We have many functions that can be implemented, such as substr, preg_replace, substr_replace, etc. Below I will introduce an example for each of these three functions, mainly talking about phone calls. ID card.

Mobile phone number string is replaced with asterisk code:

The code is as follows
 代码如下 复制代码

$str = "15832818835";
echo substr($str,0,3).'*****'.substr($str,8,strlen($str));//保留前三位和后三位
?>

或用正则

$s='www.bKjia.c0m的王经理:13999312365 李经理:13588958741';
$s=preg_replace('#(d{3})d{5}(d{3})#', '*****', $s);
echo $s;
//王经理:139*****365 李经理:135*****741
?>

Copy code


代码如下 复制代码

function half_replace($str){
$len = strlen($str)/2;
return substr_replace($str,str_repeat('*',$len),ceil(($len)/2),$len);
}

echo half_replace('test'),"n",half_replace('tests'),"n",half_replace('exceptions');

$str = "15832818835";

echo substr($str,0,3).'*****'.substr($str,8,strlen($str));//Retain the first three digits and the last three digits

?>
 代码如下 复制代码

echo strlen($idcard)==15?substr_replace($idcard,"****",8,4):(strlen($idcard)==18?substr_replace($idcard,"****",10,4):"bKjia.c0m提示身份证位数不正常!");

or use regular expression $s='Manager Wang of www.bKjia.c0m: 13999312365 Manager Li: 13588958741';

$s=preg_replace('#(d{3})d{5}(d{3})#', '${1}*****${2}', $s);

echo $s; ?> Replace the character in the middle of the string with an asterisk
The code is as follows Copy code
function half_replace($str){ $len = strlen($str)/2; Return substr_replace($str,str_repeat('*',$len),ceil(($len)/2),$len);
}
echo half_replace('test'),"n",half_replace('tests'),"n",half_replace('exceptions'); Start the PHP ID number
The code is as follows Copy code
echo strlen($idcard)==15?substr_replace($idcard,"****",8,4):(strlen($idcard)==18?substr_replace($idcard,"**** ",10,4):"bKjia.c0m prompts that the number of ID cards is abnormal! "); http://www.bkjia.com/PHPjc/633116.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/633116.htmlTechArticleReplace the character at the specified position in the string in php with an asterisk. We have many functions that can be implemented. If there is substr , preg_replace, substr_replace, etc. Below I will introduce each of these three functions...
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