Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all characters except first one and whitespaces

Hi I trying do something like that:

I've got some string - 'Hello World!' for example. And I want replace all character in it except the first one and white spaces.

so... result will be: "H.... ......"; I don't want delete it, just replacing with "." or other character.

I tried doing this with preg_replace but with no results.

like image 721
Pablo Avatar asked May 18 '26 16:05

Pablo


1 Answers

You can do it like so:

$hidden = preg_replace('/(?!^)\S/', '.', $text);

It works by ensuring that we aren't at the beginning of the string with a negative lookahead for the start of string anchor, then matches a non-whitespace character using the negated whitespace character class.

like image 165
Sebastian Paaske Tørholm Avatar answered May 21 '26 12:05

Sebastian Paaske Tørholm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!