Replace some characters with Asterisks in PHP using str_repeat().
The str_repeat() function is an inbuilt function in PHP used to repeat string in a specified number of times.
I used this recently in a project and I thought the need to share.
This function comes in handy so it depends on the purpose of the moment.
In this post, I am going to show us how to use this function to mask part of a phone number, if you don’t want to display them all. Just like this:-
This seems to be a very simple task to accomplish, but can be very confusing if not properly checked and implemented.
SYNTAX: str_repeat (string
$input , int
input: The string to be repeated
multiplier: Number of times the input string should be repeated .
Note: Multiplier must be greater than or equal to 0. And if the multiplier is set to 0 the str_repeat() function will return an empty string.
echo str_repeat(“+”, 10);
This will give a result of
WITH OTHER FUNCTIONS
Interestingly, str_repeat() can be combined with other PHP functions to achieve desired results. So, I will use substr() and strlen in addition with str_repeat() to achieve the objective of this post.
CREATING A FUNCTION TO DISPLAY MASKED NUMBER
To mask part of the number, I will create a function for that purpose.
$mask_number = str_repeat("*", strlen($number)-4) . substr($number, -4);
This function will output
Use case of this function might be different in your own application. Hope this helps. Kindly drop me a line and hit the heart button if you found this post helpful.