Created
January 17, 2019 08:54
-
-
Save Erth0/5858796b0368079044c490655f031261 to your computer and use it in GitHub Desktop.
PHP Initials Class
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 Initials | |
{ | |
/** | |
* Generate initials from a name | |
* | |
* @param string $name | |
* @return string | |
*/ | |
public function generate(string $name) : string | |
{ | |
$words = explode(' ', $name); | |
if (count($words) >= 2) { | |
return strtoupper(substr($words[0], 0, 1) . substr(end($words), 0, 1)); | |
} | |
return $this->makeInitialsFromSingleWord($name); | |
} | |
/** | |
* Make initials from a word with no spaces | |
* | |
* @param string $name | |
* @return string | |
*/ | |
protected function makeInitialsFromSingleWord(string $name) : string | |
{ | |
preg_match_all('#([A-Z]+)#', $name, $capitals); | |
if (count($capitals[1]) >= 2) { | |
return substr(implode('', $capitals[1]), 0, 2); | |
} | |
return strtoupper(substr($name, 0, 2)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment