REGEX to mask all characters except the first and last character
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);
anyone looking for masking all letters but first of every word in given sentence:
function maskele($in){
$kelimeler=explode(" ",$in);
$isim=null;
foreach ($kelimeler as $kelime){
$length = strlen($kelime);
$out = $kelime[0] . str_repeat('*', $length - 1) ;
$isim.=$out. " ";
}
return $isim;
}
精彩评论