简体   繁体   中英

php regex replace each character with asterisk

I am trying to something like this.

Hiding users except for first 3 characters.

EX)

  • apple -> app**
  • google -> goo***
  • abc12345 ->abc*****

I am currently using php like this:

$string = "abcd1234";
$regex = '/(?<=^(.{3}))(.*)$/';
$replacement = '*';
$changed = preg_replace($regex,$replacement,$string);
echo $changed;

and the result be like:

abc*

But I want to make a replacement to every single character except for first 3 - like:

abc*****

How should I do?

Don't use regex, use substr_replace :

$var = "abcdef";
$charToKeep = 3;
echo strlen($var) > $charToKeep ?  substr_replace($var, str_repeat ( '*' ,  strlen($var) - $charToKeep), $charToKeep) : $var;

Keep in mind that regex are good for matching patterns in string, but there is a lot of functions already designed for string manipulation.

Will output:

abc***

Try this function. You can specify how much chars should be visible and which character should be used as mask:

$string = "abcd1234";

echo hideCharacters($string, 3, "*");

function hideCharacters($string, $visibleCharactersCount, $mask)
{
    if(strlen($string) < $visibleCharactersCount)
        return $string;

    $part = substr($string, 0, $visibleCharactersCount);
    return str_pad($part, strlen($string), $mask, STR_PAD_RIGHT);
}

Output:

abc*****

Your regex matches all symbols after the first 3, thus, you replace them with a one hard-coded * .

You can use

'~(^.{3}|(?!^)\G)\K.~'

And replace with * . See the regex demo

This regex matches the first 3 characters (with ^.{3} ) or the end of the previous successful match or start of the string (with (?!^)\\G ), and then omits the characters matched from the match value (with \\K ) and matches any character but a newline with . .

See IDEONE demo

$re = '~(^.{3}|(?!^)\G)\K.~'; 
$strs = array("aa","apple", "google", "abc12345", "asdddd"); 
foreach ($strs as $s) {
    $result = preg_replace($re, "*", $s);
    echo $result . PHP_EOL;
}

Another possible solution is to concatenate the first three characters with a string of * repeated the correct number of times:

$text = substr($string, 0, 3).str_repeat('*', max(0, strlen($string) - 3));

The usage of max() is needed to avoid str_repeat() issue a warning when it receives a negative argument. This situation happens when the length of $string is less than 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM