Skip to content

Instantly share code, notes, and snippets.

@effone
Last active January 4, 2022 13:58
Show Gist options
  • Save effone/9cabb71e1b81dbd6493f2a0eaddfd6f7 to your computer and use it in GitHub Desktop.
Save effone/9cabb71e1b81dbd6493f2a0eaddfd6f7 to your computer and use it in GitHub Desktop.

Revisions

  1. effone revised this gist Aug 18, 2018. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions func.abb.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    <?php

    /**
    * Generate 3-letter abbreviation
    * @author effone <[email protected]>
  2. effone created this gist Aug 18, 2018.
    33 changes: 33 additions & 0 deletions func.abb.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    /**
    * Generate 3-letter abbreviation
    * @author effone <[email protected]>
    *
    * @param string $string
    * @return string
    */
    function abb($string = '')
    {
    $vowels = array('A', 'E', 'I', 'O', 'U');
    $string = preg_replace('/[^A-Z ]/u', '', strtoupper(strip_tags($string))); // Sanitize, capitalize, remove numbers and special characters
    $str_array = explode(' ', $string);

    if (sizeof($str_array) > 2) {
    $string = '';
    foreach ($str_array as $word) {
    $string .= substr($word, 0, 1);
    }
    } else if (sizeof($str_array) == 2) {
    $string = substr($str_array[0], 0, 1);
    $string .= substr($str_array[1], 0, 1) . substr($str_array[1], -1);
    } else {
    $first_char = substr($string, 0, 1);
    $last_char = substr($string, -1);
    $last_char = in_array($last_char, $vowels) ? substr($string, -2, 1) : $last_char; // Consider second last if last one is vowel
    $string = str_replace($vowels, '', substr($string, 1, -1)); // Removefirst and last character, all vowels and spaces from middle section of string
    $string = strlen($string) > 1 ? substr($string, (ceil(strlen($string) / 2) - 1), 1) : $string;
    $string = $first_char . $string . $last_char;
    }

    $string = strlen($string) > 3 ? abb($string) : $string; // Re-abbreviate if character is more than 3
    return $string;
    }