开发者

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

开发者 https://www.devze.com 2023-01-07 13:13 出处:网络
Example Input: SMK SUNGAI PUNAI My Code: $school = \'SMK SUNGAI PUNAI\'; echo ucwords(strtolower($school));

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?


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.


You can very simply create a pipe-delimited set of excluded words/acronyms, then use (*SKIP)(*FAIL) to prevent matching those whole words.

mb_convert_case() is an excellent function to call because it instantly provides TitleCasing and it is multibyte safe.

Code: (Demo)

$pipedExclusions = 'SMK|USA|AUS';
echo preg_replace_callback(
         '~\b(?:(?:' . $pipedExclusions . ')(*SKIP)(*FAIL)|\p{Lu}+)\b~u',
         fn($m) => mb_convert_case($m[0], MB_CASE_TITLE),
         'SMK SUNGAI PUNAI'
     );
// SMK Sungai Punai


There's no really good way to do it. In this case you can assume it's an abbreviation because it's only three letters long and contains no vowels. You can write a set of rules that look for abbreviations in the string and then uppercase them, but in some cases it'll be impossible... consider "BOB PLAYS TOO MUCH WOW."


You can use something like this:

<?php
$str = 'SMK SUNGAI PUNAI';
$str = strtolower($str);
$arr = explode(" ", $str);

$new_str = strtoupper($arr[0]). ' ' .ucfirst($arr[1]). ' ' .ucfirst($arr[2]);
echo '<p>'.$new_str.'</p>';

// Result: SMK Sungai Punai
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消