Search code examples
phpstringblacklistacronymtitle-case

Apply title-case to all words in string except for nominated acronyms


Example Input: SMK SUNGAI PUNAI

My Code:

$school = 'SMK SUNGAI PUNAI';
echo ucwords(strtolower($school));

Unwanted Output: Smk Sungai Punai

Question

How to make the output SMK Sungai Punai which allows SMK to remain in ALL-CAPS.

Update.

The problem I have list of 10,000 school names. From PDF, I convert to mysql. I copied exactly from PDF the name of schools -- all in uppercase.

How can I implement conditional title-casing?


Solution

  • As far as I understand you want to have all school names with the first character of every word in uppercase and exclude some special words ($exceptions in my sample) from this processing.

    You could do that like this:

       function createSchoolName($school) {
          $exceptions = array('SMK', 'PTS', 'SBP');
          $result = "";
          $words = explode(" ", $school);
          foreach ($words as $word) {
              if (in_array($word, $exceptions))
                  $result .= " ".$word;
              else
                  $result .= " ".strtolower($word);
          }
          return trim(ucwords($result));
       }
    
    echo createSchoolName('SMK SUNGAI PUNAI');
    

    This example would return SMK Sungai Punai as required by your question.