Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX to mask all characters except the first and last character

Tags:

regex

php

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?

like image 348
Sujit Agarwal Avatar asked Dec 27 '22 19:12

Sujit Agarwal


2 Answers

Why not use str_repeat()?

$length = strlen($in); 
$out = $in[0] . str_repeat('*', $length - 2) . $in[$length-1]; 
like image 120
Denis de Bernardy Avatar answered Dec 30 '22 09:12

Denis de Bernardy


This is the regex you want:

$string='asdfbASDF1234';
echo $string."\n";
echo preg_replace('/(?!^.?).(?!.{0}$)/', '*', $string);
like image 38
guido Avatar answered Dec 30 '22 08:12

guido