I want to mask all the characters of a string except the first and last character. I tried something like this:
<?php
$count = 0;
$string='asdfbASDF1234';
echo preg_replace('/(?!^)\S/', '*', $string, -1 , $count);
?>
It is masking all characters except the first one. What is the proper regex for this?
Why not use str_repeat()
?
$length = strlen($in);
$out = $in[0] . str_repeat('*', $length - 2) . $in[$length-1];
This is the regex you want:
$string='asdfbASDF1234';
echo $string."\n";
echo preg_replace('/(?!^.?).(?!.{0}$)/', '*', $string);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With