Hide part of phone in the string php

Viewed 26

supouse that i have this string

(111) 222-3333 fgbv 1112223333 111 222-3333 fghgg 111-222-3333 jony13@gmail.com fghntyjn (111)2223333 +11234567890 1-8002353551 123-456-7890 -Hello! +1 - 1234567890

string

How i can hide part of the numbers and emails

Asi the result that i need

(111) 222-3xxx fgbv 1112223xxx 111 222-3xxx fghgg 111-222-3xxx jonxxx@xxxil.com fghntyjn (111)2223xxx +11234567xxx 1-8002353xxx 123-456-7xxx -Hello! +1 - 1234567xxx string

1 Answers

You should analyze both your input string and your desired output string and check for patterns, that you can match programmatically.

In this case, you would probably split the input down to smaller chunks that you can process individually.

For each target, you can then check how you want to handle it.

In your case, it is probably a good idea to split at white spaces and then check if you are handling a phone number or en email address, or something that should not be touched at all.

Here is a sample implementation of the described algorithmen:

<?php

$in = '(111) 222-3333 fgbv 1112223333 111 222-3333 fghgg 111-222-3333 jony13@gmail.com fghntyjn (111)2223333 +11234567890 1-8002353551 123-456-7890 -Hello! +1 - 1234567890';

$out = '(111) 222-3xxx fgbv 1112223xxx 111 222-3xxx fghgg 111-222-3xxx jonxxx@xxxil.com fghntyjn (111)2223xxx +11234567xxx 1-8002353xxx 123-456-7xxx -Hello! +1 - 1234567xxx';

/**
 * Write a function that transforms the input string into the output string.
 */
function transform(string $in): string
{
    $parts = explode(' ', $in);

    $processedParts = array_map(
        array: $parts,
        callback: function (string $part): string {
            // Is email?
            if (filter_var($part, FILTER_VALIDATE_EMAIL)) {
                // Split email into parts on @
                $emailParts = explode('@', $part);

                // Replace last three characters with xxx of first part
                $emailParts[0] = substr($emailParts[0], 0, -3) . 'xxx';

                // Replace first three characters with xxx of second part
                $emailParts[1] = 'xxx' . substr($emailParts[1], 3);

                // Join the parts back together
                return implode('@', $emailParts);
            }
            // Is min 6 chars and has at least one digit?
            else if (
                strlen($part) >= 6 && preg_match('/\d/', $part)
            ) {
                // Replace last three characters with xxx
                return substr($part, 0, -3) . 'xxx';
            }

            return $part;
        },
    );

    return implode(' ', $processedParts);
}

$fnOut = transform(in: $in);

echo $fnOut . PHP_EOL;

// Is the output the same as the expected output?
echo $out == $fnOut ? 'PASS' : 'FAIL';
Related