How to hide the middle four digits of a number in php

王林
Release: 2023-03-04 21:00:02
Original
2699 people have browsed it

php实现隐藏数字中间四位的方法:可以利用substr_replace()函数来实现。substr_replace()函数可以把字符串的一部分替换为另一个字符串,并返回被替换的字符串。

How to hide the middle four digits of a number in php

substr_replace() 函数把字符串的一部分替换为另一个字符串,并返回被替换的字符串。如果 string 是数组,则返回数组。

(推荐教程:php图文教程

语法:

substr_replace(string,replacement,start,length)
Copy after login

参数:

  • string 必需。规定要检查的字符串。

  • replacement 必需。规定要插入的字符串。

  • start 必需。规定在字符串的何处开始替换。

正数 - 在字符串中的指定位置开始替换

负数 - 在从字符串结尾的指定位置开始替换

0 - 在字符串中的第一个字符处开始替换

  • length 可选。规定要替换多少个字符。默认是与字符串长度相同。

正数 - 被替换的字符串长度

负数 - 表示待替换的子字符串结尾处距离 string 末端的字符个数

0 - 插入而非替换

(学习视频推荐:php视频教程

实现代码:

<?php
$tel = &#39;12345678910&#39;;
//1.字符串截取法
$new_tel1 = substr($tel, 0, 3).&#39;****&#39;.substr($tel, 7);
var_dump($new_tel1);
//2.替换字符串的子串
$new_tel2 = substr_replace($tel, &#39;****&#39;, 3, 4);
var_dump($new_tel2);
//3.用正则
$new_tel3 = preg_replace(&#39;/(\d{3})\d{4}(\d{4})/&#39;, &#39;$1****$2&#39;, $tel);
var_dump($new_tel3);
?>
Copy after login

输出结果:

> string(11) "123****8910"
> string(11) "123****8910"
> string(11) "123****8910"
Copy after login

The above is the detailed content of How to hide the middle four digits of a number in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!