Created
April 27, 2017 08:01
-
-
Save FlorianWeigang/5e5f168d1370e0771e7b181b033bb912 to your computer and use it in GitHub Desktop.
This class generates nicknames out of an email address. This is useful if you have an interface and you dont want to show the email addresses of your customers / users to the world. It cuts the first part of your email address and checks if there are two different names present in the first part and takes the first char of the first two found na…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Class NickNameGenerator | |
| * | |
| * Example: | |
| * | |
| * email@example.com => EM | |
| * email.demo@example.com => ED | |
| * email-first-demo@example.com => EF | |
| * | |
| * Supported delimiter: ",", ".", "_", "-" | |
| * | |
| * @author Florian Weigang | |
| */ | |
| class NickNameGenerator | |
| { | |
| /** | |
| * @param $email | |
| * @return string|void | |
| */ | |
| public static function generateNicknameByEmail($email) | |
| { | |
| $arr = explode("@", $email); | |
| if(count($arr) < 2) { | |
| return $email; | |
| } | |
| $firstPart = $arr[0]; | |
| if (strlen($firstPart) < 3) { | |
| return strtoupper($firstPart); | |
| } | |
| foreach ([',', '.', '_', '-'] as $delimiter) { | |
| $nick = self::tryExplodeBy($firstPart, $delimiter); | |
| if ($nick) { | |
| return $nick; | |
| } | |
| } | |
| return strtoupper(substr($firstPart, 0, 2)); | |
| } | |
| /** | |
| * @param $string | |
| * @param $delimiter | |
| * | |
| * @return bool | |
| */ | |
| private static function tryExplodeBy($string, $delimiter) | |
| { | |
| $parts = explode($delimiter, $string); | |
| if (count($parts) < 2) { | |
| return false; | |
| } | |
| $first = $parts[0]; | |
| $second = $parts[1]; | |
| if (strlen($first) < 1 || strlen($second) < 1) { | |
| return false; | |
| } | |
| return strtoupper(substr($first, 0, 1) . substr($second, 0, 1)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment