1

我需要将一些字符串/句子转换为小写,例如:“ ȘEF DE CABINET ”,然后仅将这些字符串的第一个单词(带有变音符号)的第一个字母转换为大写。我找到了一个函数,可以转换字符串中每个单词的第一个字母。如何使其适应我的需求?

这是代码:

function sentence_case( $s ) {
   $s = mb_convert_case( $s, MB_CASE_LOWER, 'UTF-8' );
   $arr = preg_split("//u", $s, -1, PREG_SPLIT_NO_EMPTY);
   $result = "";
   $mode = false;
   foreach ($arr as $char) {
      $res = preg_match(
         '/\\p{Mn}|\\p{Me}|\\p{Cf}|\\p{Lm}|\\p{Sk}|\\p{Lu}|\\p{Ll}|'.
         '\\p{Lt}|\\p{Sk}|\\p{Cs}/u', $char) == 1;
      if ($mode) {
         if (!$res)
            $mode = false;
      } 
      elseif ($res) {
         $mode = true;
         $char = mb_convert_case($char, MB_CASE_TITLE, "UTF-8");
      }
      $result .= $char;
   }

   return $result; 
}
4

2 回答 2

2

最后,这是我用过的(感谢@ben-pearl-kahan 的正确方向!):

function sentence_case( $string ) {
   $string = mb_strtolower( $string, 'UTF-8' ); //convert the string to lowercase
   $string_len = mb_strlen( $string, 'UTF-8' ); //calculate the string length
   $first_letter = mb_substr( $string, 0, 1, 'UTF-8' ); //get the first letter of the string
   $first_letter = mb_strtoupper( $first_letter, 'UTF-8' ); //convert the first letter to uppercase
   $rest_of_string = mb_substr( $string, 1, $string_len, 'UTF-8' ); //get the rest of the string
   return $first_letter . $rest_of_string; //return the string converted to sentence case
}
于 2013-09-16T20:03:32.467 回答
1

用于substr仅检索第一个字符并对其进行操作:

function sentence_case( $x ) {
   $s = substr($x,0,1);
   $s = mb_convert_case( $s, MB_CASE_LOWER, 'UTF-8' );
   $arr = preg_split("//u", $s, -1, PREG_SPLIT_NO_EMPTY);
   $result = "";
   $mode = false;
   foreach ($arr as $char) {
      $res = preg_match(
         '/\\p{Mn}|\\p{Me}|\\p{Cf}|\\p{Lm}|\\p{Sk}|\\p{Lu}|\\p{Ll}|'.
         '\\p{Lt}|\\p{Sk}|\\p{Cs}/u', $char) == 1;
      if ($mode) {
         if (!$res)
            $mode = false;
      } 
      elseif ($res) {
         $mode = true;
         $char = mb_convert_case($char, MB_CASE_TITLE, "UTF-8");
      }
      $result .= $char;
   }

   return $result.substr($x,1); 
}
于 2013-09-15T22:54:31.200 回答