DEV Community

Wallace Maxters
Wallace Maxters

Posted on

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)