How do you replace every characters in a string with asterisk except the first and last characters?

To be more specific, how to you obfuscate an email address partially but still make it recognizable ? An example is [email protected] becomes j******[email protected]

Regrex or preg_replace to perform a regular expressions search and replace. Inspired by a regex example.
php > $regex = "/(?<!^)\S(?!$)/";
php > echo preg_replace($regex, '.', 'johndoe'), "\n";
php >

Break down of the regex and explanation of each part.
(?<!^)  # not the first character
\S       # matches any string but a whitespace
(?!$)    # not the last character

Both (?<!pattern) and (?!pattern) are look-behind and look-ahead assertion. Assertion are test on characters before or after the matched pattern. In our case here, we want all characters that is not in the first and last position.

More details breakdown and explanation using explain, a regular expression online tools. Result as shown:
(?lt;!  # look behind to see if there is not:
^      # the beginning of the string
)       # end of look-behind
\S     # non-whitespace (all but \n, \r, \t, \f, and " ")
(?!     # look ahead to see if there is not:
$       # before an optional \n, and the end of the string
)        # end of look-ahead

No comments:

Post a Comment