Home Backend Development PHP Tutorial 利用PHP将部分内容用星号替换_php实例

利用PHP将部分内容用星号替换_php实例

Jun 07, 2016 pm 05:12 PM
php string replacement

在最近的项目中,会碰到到某人的手机号码隐藏中间几位,身份证号码只显示末尾4位的需求。当时一开始是网上搜索了一下,看到有人是用substr_replace这个函数来替换的,后面我也用了这个函数,但在用的时候不是很好用。

一、substr_replace
先来看看这个函数的语法:

复制代码 代码如下:
substr_replace(string,replacement,start,length)
参数 描述
string 必需。规定要检查的字符串。
replacement 必需。规定要插入的字符串。
start

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

 正数 - 在第 start 个偏移量开始替换

 负数 - 在从字符串结尾的第 start 个偏移量开始替换

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

charlist

可选。规定要替换多少个字符。

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

  负数 - 从字符串末端开始的被替换字符数

  0 - 插入而非替换

1、当start与charlist都为正数的时候,非常好理解,也很符号人的逻辑,start是从0开始的,如下图,根据条件,绿色的将是要被替换的元素

2、当start为负数,charlist为正数的时候,也挺好理解的

3、当start为正数,charlist为负数的时候,这个我一开始理解错了

4、当start为负数,charlist为负数的时候,有一个地方需要注意的就是:如果 start 是负数且 length 小于等于 start,则 length 为 0。这个坑挺容易踩到的

5、charlist为0的时候,就变成插入了,而不是替换,额。。。

 

用下来,我是感觉不是很顺手,虽然说满足我现在的需求还是可以的,但是如果将来需要一些扩展的话,耍起来挺吃力的,所以就想到自己构造一个,将来用起来也方便。

二、自制的星号替换函数

复制代码 代码如下:
replaceStar($str, $start, $length = 0)

前面的两个参数与上面的一样,最后的参数与上面不同

1、当start与length都为正数,与substr_replace表现的一样

2、当start为负数,length为正数,与substr_replace表现的一样

三、源码分享

public static function replaceStar($str, $start, $length = 0)
{
  $i = 0;
  $star = '';
  if($start >= 0) {
   if($length > 0) {
    $str_len = strlen($str);
    $count = $length;
    if($start >= $str_len) {//当开始的下标大于字符串长度的时候,就不做替换了
     $count = 0;
    }
   }elseif($length < 0){
    $str_len = strlen($str);
    $count = abs($length);
    if($start >= $str_len) {//当开始的下标大于字符串长度的时候,由于是反向的,就从最后那个字符的下标开始
     $start = $str_len - 1;
    }
    $offset = $start - $count + 1;//起点下标减去数量,计算偏移量
    $count = $offset >= 0 &#63; abs($length) : ($start + 1);//偏移量大于等于0说明没有超过最左边,小于0了说明超过了最左边,就用起点到最左边的长度
    $start = $offset >= 0 &#63; $offset : 0;//从最左边或左边的某个位置开始
   }else {
    $str_len = strlen($str);
    $count = $str_len - $start;//计算要替换的数量
   }
  }else {
   if($length > 0) {
    $offset = abs($start);
    $count = $offset >= $length &#63; $length : $offset;//大于等于长度的时候 没有超出最右边
   }elseif($length < 0){
    $str_len = strlen($str);
    $end = $str_len + $start;//计算偏移的结尾值
    $offset = abs($start + $length) - 1;//计算偏移量,由于都是负数就加起来
    $start = $str_len - $offset;//计算起点值
    $start = $start >= 0 &#63; $start : 0;
    $count = $end - $start + 1;
   }else {
    $str_len = strlen($str);
    $count = $str_len + $start + 1;//计算需要偏移的长度
    $start = 0;
   }
  }

  while ($i < $count) {
   $star .= '*';
   $i++;
  }

  return substr_replace($str, $star, $start, $count);
}


Copy after login

不擅长算法,这里就用很普通的逻辑来展示啦,没有用到啥数学公式。

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');
 }

Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles