Thursday 31 March 2016

Get All First Letters or Abbreviation of Each Words of the sentence as a Abbreviated String using PHP

Please use the below function to pull all First Letters of Each Words of the sentence as a abbreviated String using PHP.

/**
 * Get the first letters or abbreviation of each words and as a uppercase string format.
 * @param $string Pass the parsing string
 * @return string String
 */
function getFirstLettersOfWords($string) {}
OR 
function getStringAbbreviation($string) 
{
 // Match the first letters of each words using regular expression.
 $matchFound= preg_match_all('/(\w)(\w+)/', $string, $matches);

 // Concatenate all the matched first letters as a string in upper case.
 $abbreviatedString= strtoupper( implode('', $matches[1]) );

 return $abbreviatedString;
}

Function Usage

$string1 = 'Distributor / Sub-Distributor';
$output1 = getStringAbbreviation($string1);

// Output: DSD

$string2 = 'Consultant (Registration, Licensing, Visa)';
$output2 = getStringAbbreviation($string2);

// Output: CRLV

No comments:

Post a Comment

Please post any queries and comments here.