繁体   English   中英

如何在PHP中大写字符串的第一个字母(带有变音符号)?

[英]How to capitalize the first letter (with a diacritic) of string in PHP?

我需要将某些字符串/句子转换为小写,例如:“ Ș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; 
}

使用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); 
}

最后,这就是我用过的(感谢@ 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM