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:-

Masked phone number with asterisks

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 $multiplier)

PARAMETERS

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.

Example

<?php
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.

<?php
function maskPhoneNumber($number){

$mask_number = str_repeat("*", strlen($number)-4) . substr($number, -4);

return $mask_number;
}
echo maskPhoneNumber('08066417364');
?>

This function will output

*******7364

WRAPPING UP

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.