How to replace all characters of string to asterisks except first and last characters in PHP?
For example test should become t**t and profanity become p******y and so on,
Use the above code. This will fulfill your requirement.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function get_starred($str) { $len = strlen($str); return substr($str, 0, 1).str_repeat('*', $len - 2).substr($str, $len - 1, 1); } $myStr = 'YourName'; echo get_starred($myStr); //should show Y******e |
Another code, Here a small function:
1 2 3 4 5 6 7 8 9 10 11 |
function asterisks($toConvert) { $astNumber = strlen($toConvert) - 2; return substr($toConvert, 0, 1) . str_repeat("*", $astNumber) . substr($toConvert, -1); } $tempString= 'teststring'; echo asterisks($tempString); |
This will replace the first and last like *bcdefghijklm* characters from variable $text;
1 2 3 4 5 6 7 |
$text = 'abcdefghijklmn'; $count = strlen($text)-1; echo str_replace(array($text[0], $text[$count]), '*', $text); |