0

How can I echo $name so that only the first 5 characters are shown as alphabets and the rest are shown as *-marks. For example echo $name prints 'Test ***' not 'Test Guy'?

Robin
  • 8,162
  • 7
  • 56
  • 101
dggdsdg
  • 27
  • 2
  • 2
  • 3

2 Answers2

2

I would prefer str_pad() over regex functions in this case:

$pattern = 'Test Guy';
echo str_pad(substr($pattern,0,4), strlen($pattern), '*');

Easier, since padding is what you want to do, and offering better performance, since no slow regexes have to be compiled and applied...

arkascha
  • 41,620
  • 7
  • 58
  • 90
0

In your case (looks like you want to replace all characters except 'space' with '*') you can use this.

$str = "Test Guy";
echo substr($str, 0, 4) . preg_replace('/[^\s]/', '*', substr($str, 4));

output: Test ***

It's a little bit universal and you can use it with another strings like:

$str = "This is random string";
echo substr($str, 0, 4) . preg_replace('/[^\s]/', '*', substr($str, 4));

output: This ** ****** ******

I guess next that you have to do it wrap this code to the function like so:

function get_strange_string($str, $clear = 4) {
    return substr($str, 0, $clear) 
           . preg_replace('/[^\s]/', '*', substr($str, $clear));
}
KryDos
  • 447
  • 4
  • 14