Skip to content

Instantly share code, notes, and snippets.

@cmanish049
Created January 17, 2019 11:19
Show Gist options
  • Save cmanish049/c88ee38708297b5a43703fd0f2c801be to your computer and use it in GitHub Desktop.
Save cmanish049/c88ee38708297b5a43703fd0f2c801be to your computer and use it in GitHub Desktop.
Initials
<?php
class Initials
{
/**
* Generate initials from a name
* @param string name
* @return string
*/
public function generate(string $name)
{
$words = epode(' ', $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
* @param string name
* @return string
*/
public function makeInitialsFormSingleWord(string $name)
{
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