Function to mask numbers and strings in PHP
Wallace Maxters

Wallace Maxters @wallacemaxters

About: Full stack Web Developer

Location:
Brazil
Joined:
Feb 6, 2021

Function to mask numbers and strings in PHP

Publish Date: Nov 14 '22
2 0

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

Comments 0 total

    Add comment