Replace with stars part of a string in PHP

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 107

Replace with stars part of a string in PHP

Hello
How can I replace part of a string with stars in php?
For example: "marplo" to turn into "m***lo".

Admin Posts: 805
Hello
Try the function from this example:

Code: Select all

// Replace in $str the characters starting from $first (0 first character) to $last, with $rep
function repStr($str, $first=0, $last=0, $rep='*'){
  $begin = substr($str,0,$first);
  $middle = str_repeat($rep,strlen(substr($str,$first,$last)));
  $end = substr($str,$last);
  $stars = $begin.$middle.$end;
  return $stars;
}

$str ='marplo';

//replace in $str the characters from index 1 till the last two characters
$str2 = repStr($str, 1, -2);
echo $str2;  // m***lo