Table of Contents
PHP replaces part of the content with asterisks
Home Backend Development PHP Tutorial PHP replaces part of the content with asterisks_PHP tutorial

PHP replaces part of the content with asterisks_PHP tutorial

Jul 13, 2016 am 10:19 AM
content part

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 < 0){
$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 < 0){
$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 < $count) {
$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 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

Video Face Swap

Video Face Swap

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

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)

How to enable Sensitive Content Warning on iPhone and learn about its features How to enable Sensitive Content Warning on iPhone and learn about its features Sep 22, 2023 pm 12:41 PM

Especially over the past decade, mobile devices have become the primary way to share content with friends and family. The easy-to-access, easy-to-use interface and ability to capture images and videos in real time make it a great choice for creating and sharing content. However, it's easy for malicious users to abuse these tools to forward unwanted, sensitive content that may not be suitable for viewing and does not require your consent. To prevent this from happening, a new feature with "Sensitive Content Warning" was introduced in iOS17. Let's take a look at it and how to use it on your iPhone. What is the new Sensitive Content Warning and how does it work? As mentioned above, Sensitive Content Warning is a new privacy and security feature designed to help prevent users from viewing sensitive content, including iPhone

How to change the Microsoft Edge browser to open with 360 navigation - How to change the opening with 360 navigation How to change the Microsoft Edge browser to open with 360 navigation - How to change the opening with 360 navigation Mar 04, 2024 pm 01:50 PM

How to change the page that opens the Microsoft Edge browser to 360 navigation? It is actually very simple, so now I will share with you the method of changing the page that opens the Microsoft Edge browser to 360 navigation. Friends in need can take a look. I hope Can help everyone. Open the Microsoft Edge browser. We see a page like the one below. Click the three-dot icon in the upper right corner. Click "Settings." Click "On startup" in the left column of the settings page. Click on the three points shown in the picture in the right column (do not click "Open New Tab"), then click Edit and change the URL to "0" (or other meaningless numbers). Then click "Save". Next, select "

How to set up Cheat Engine in Chinese? Cheat Engine setting Chinese method How to set up Cheat Engine in Chinese? Cheat Engine setting Chinese method Mar 13, 2024 pm 04:49 PM

CheatEngine is a game editor that can edit and modify the game's memory. However, its default language is non-Chinese, which is inconvenient for many friends. So how to set Chinese in CheatEngine? Today, the editor will give you a detailed introduction to how to set up Chinese in CheatEngine. I hope it can help you. Setting method one: 1. Double-click to open the software and click "edit" in the upper left corner. 2. Then click “settings” in the option list below. 3. In the opened window interface, click "languages" in the left column

Where to set the download button in Microsoft Edge - How to set the download button in Microsoft Edge Where to set the download button in Microsoft Edge - How to set the download button in Microsoft Edge Mar 06, 2024 am 11:49 AM

Do you know where to set the download button to display in Microsoft Edge? Below, the editor will bring you the method to set the download button to display in Microsoft Edge. I hope it will be helpful to you. Let’s follow the editor to learn it! Step 1: First open Microsoft Edge Browser, click the [...] logo in the upper right corner, as shown in the figure below. Step 2: Then click [Settings] in the pop-up menu, as shown in the figure below. Step 3: Then click [Appearance] on the left side of the interface, as shown in the figure below. Step 4: Finally, click the button on the right side of [Show Download Button] and it will change from gray to blue, as shown in the figure below. The above is where the editor brings you how to set up the download button in Microsoft Edge.

How can we put three parts side by side in HTML? How can we put three parts side by side in HTML? Sep 04, 2023 pm 11:21 PM

Tags define the divisions of an HTML document. This tag is primarily used to group similar content together for easy styling, and also serves as a container for HTML elements. We use CSS properties to place three section tags side by side in HTML. The CSS property float is used to achieve this purpose. Syntax Below is the syntax for the <div> tag. <divclass='division'>Content…</div>The Chinese translation of Example1 is: Example 1 The following is an example of using CSS properties to place three division classes side by side in HTML. <!DOCTYPEhtml><html><

The daily life of Ain, a traveler in space and time: permanent content update The daily life of Ain, a traveler in space and time: permanent content update Mar 01, 2024 pm 08:37 PM

The Painted Traveler in Time and Space has been confirmed to be updated on February 29th. Players can go to the open-air music festival with Ain to gain a favorability bonus with Ain. On March 4th, the Lingering Holiday Color Time event will be launched. , players can upgrade their holiday itinerary level to unlock new text messages and Lofter content. The Daily Life of Ain, a Traveler in Time and Space: Permanent Content Update After the February 29 version, you can experience the new campus schedule [Participate in the Open Air Music Festival], and you can get a favorability bonus by participating with Ain. From 09:30 on March 4th to 05:00 on April 15th, during the "Longening Holiday·Sexy Time" event, upgrade the [Holiday Itinerary] level to level 8 and level 28 to unlock new text messages and Lofter content respectively. *New SMS and Lofter added

Analyzing Solana's DEX layout: Is Jupiter the future of ecology? Analyzing Solana's DEX layout: Is Jupiter the future of ecology? Mar 26, 2024 pm 02:10 PM

Source: Shenchao TechFlow As a high-profile emerging project in the Solana ecosystem, Jupiter has quickly emerged in the DeFi field despite its short launch. However, even in such a rapidly developing environment, the improvement of economic models and the stability of token prices are still crucial. Without these supports, a project can easily fall into a vicious cycle that may ultimately lead to its decline or even its inability to sustain itself. Therefore, Jupiter needs to continuously optimize its economic design and ensure token price stability to ensure the long-term development and success of the project. The Solana chain has performed strongly in the past week, with its token SOL rising rapidly in the secondary market, and Jupiter’s token $JUP also rising in the past two weeks.

What content is available in mind mapping online? What content is available in mind mapping online? Mar 20, 2024 am 10:43 AM

Mind mapping software, for example, is like a thinking &quot;map&quot; used in memory, learning, thinking, etc. Its emergence is conducive to the spread of thinking in the human brain. It is not difficult to find that many companies today use mind mapping to expand employees' thinking and so on. So do you know what content is available in mind maps online? Today, the editor will give a brief introduction. 1. The course catalog for this course is as shown in the figure. 2. Xmind’s theme operation attributes include theme attributes, expand theme, select all themes, and theme order. 3. Theme attributes include insert, delete, undo, copy, and paste, as shown in the figure. 4. Open the [Xmind8] software, click [New], press [Insert] to insert the next level, select [Branch] again, and press [Inse]

See all articles