DEV Community

Wallace Maxters
Wallace Maxters

Posted on

1

Function to mask numbers and strings in PHP


function mask (string $placeholder, string $value, string $char = '#'): string 
{
    $template = strtr($placeholder, [$char => '%s']);

    return sprintf($template, ...str_split($value));
}
Enter fullscreen mode Exit fullscreen mode

Explanation

The $template variable receives the value of strtr that replaces # to %s. The %s is a representation of string in sprint function.

For example, the string '(##) ####-####' will be replaced by '(%s%s) %s%s%s%s-%s%s%s%s'.

The str_split will transform the $value string in a array of characteres. In sprintf, the result of str_split call is applied as argument of sprint with ... Spread Operator.

Watch the video

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay