search
HomeBackend DevelopmentPHP TutorialPHP replaces part of the content with asterisks_PHP tutorial

PHP replaces part of the content with asterisks

In a recent project, I encountered the need to hide the middle digits of someone's mobile phone number and only display the last 4 digits of the ID number. At the beginning, I searched online and saw that someone used the substr_replace function to replace it. I also used this function later, but it was not very useful when I used it.
1. substr_replace
Let’s take a look at the syntax of this function:
substr_replace(string,replacement,start,length)
Parameters Description
string Required. Specifies the string to check.
replacement Required. Specifies the string to be inserted.
start
Required. Specifies where in the string to begin replacement.
Positive number - start replacing
at the start offset
Negative numbers - replace
starting at the start offset from the end of the string
0 - Start replacing
at the first character in the string
charlist
Optional. Specifies how many characters to replace.
Positive number - the length of the string to be replaced
Negative number - the number of characters to be replaced starting from the end of the string
0 - insert instead of replace
1. When start and charlist are both positive numbers, it is very easy to understand and symbolizes human logic. Start starts from 0, as shown below. According to the conditions, the green element will be the element to be replaced
2. When start is a negative number and charlist is a positive number, it is easy to understand
3. When start is a positive number and charlist is a negative number, I misunderstood this at first
4. When start is a negative number and charlist is a negative number, one thing to note is: if start is a negative number and length is less than or equal to start, then length is 0. This trap is quite easy to step into
5. When charlist is 0, it becomes insertion instead of replacement, eh. . .
After using it, I feel that it is not very smooth. Although it can meet my current needs, if I need some expansion in the future, it will be quite difficult to use, so I thought of constructing one myself, which will be convenient to use in the future. .
2. Homemade asterisk replacement function
replaceStar($str, $start, $length = 0)
Parameters Description
str Required. Specifies the string to check.
start
Required. Specifies where in the string to begin replacement.
Positive number - start replacing
at the start offset
Negative numbers - replace
starting at the start offset from the end of the string
0 - Start replacing
at the first character in the string
length
Optional. Specifies how many characters to replace.
Positive number - the length of the string to be replaced, from left to right
Negative number - the length of the string to be replaced, from right to left
0 - If start is a positive number, start from start and go left to the end
  - If start is a negative number, start from start and go to the right to the end
The first two parameters are the same as above, and the last parameter is different from above
1. When start and length are both positive numbers, it behaves the same as substr_replace
2. When start is a negative number and length is a positive number, it behaves the same as substr_replace
substr_replace
replaceStar
start is a positive number and length is a negative number
start is a negative number and length is a negative number
start is a positive number and the length is 0 Perform insertion operation
start is a negative number and the length is 0 Perform insertion operation
3. Source code sharing
Copy code
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 & GT; = $ Str_len) {// When the starting bid is greater than the length of the string, it will not replace it
                $count = 0;
        }
        }elseif($length
$str_len = strlen($str);
$count = abs($length);
                                                                                                                                                                                                                                                                                                   
                  $start = $str_len - 1;
        }
                                                                                                                                                                            $offset = $start - $count + 1;//Subtract the quantity from the starting point subscript and calculate the offset
                                                                                                                                         Use the length from the starting point to the far left
                                                                                                                                                                                                                                             
      }else {
$str_len = strlen($str);
                  $count = $str_len - $start;//Calculate the quantity to be replaced
      }
}else {
if($length > 0) {
$offset = abs($start);
$count = $offset >= $length ? $length : $offset;//When greater than or equal to the length, it does not exceed the rightmost
        }elseif($length
$str_len = strlen($str);
                  $end = $str_len + $start;//Calculate the end value of the offset
$offset = abs($start + $length) - 1;//Calculate the offset, since they are all negative numbers, add them up
                  $start = $str_len - $offset;//Calculate the starting value
$start = $start >= 0 ? $start : 0;
$count = $end - $start + 1;
      }else {
$str_len = strlen($str);
                  $count = $str_len + $start + 1;//Calculate the length of offset required
$start = 0;
      }
}
while ($i
$star .= '*';
$i++;
}
return substr_replace($str, $star, $start, $count);
}
Copy code
I am not good at algorithms, so I will use very common logic to show it here, without using any mathematical formulas.
1. if($start >= 0) here is the branch where start is greater than or equal to 0 and less than 0
2. Among the start points, make three branches with length greater than 0, less than 0 and equal to 0 respectively
3. Finally calculate start, count and the asterisk string to be replaced. The finally calculated start and count are both positive numbers. Use substr_replace to replace them
4. Unit Test
Copy code
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');
    }

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/871181.htmlTechArticlePHP将部分内容替换成星号 在最近的项目中,会碰到到某人的手机号码隐藏中间几位,身份证号码只显示末尾4位的需求。当时一开始是网上...
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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools