PHP资本化ALPHABET的第一封信

时间:2016-05-19 01:37:03

标签: php uppercase capitalize

ucwords和ucfirst将字符串中的第一个字符转换为大写字母。

我需要一个函数来大写字母表中的第一个字符。

例如:¡嗨! - > ¡嗨! 'h'应该是大写,因为它是字母表中的第一个字符。

西班牙语我们在单词/句子/短语的开头和结尾都有问号,因此使用ucword / ucfirst将第一个字符大写并没有解决我的问题。我需要从字符串中大写第一个字母字符。

¿你最喜欢的运动是什么? - >在ucfirst之后 - >¿你最喜欢的运动是什么?

期望的结果:

¿你最喜欢的运动是什么?

/////// ------------------ ///////更新/////// ------- ----------- ///////

感谢您的回答我能够修改它并获得最终功能。

此功能将第一个字母大写(包括此重音西班牙语元音áéíóú)

function _ucfirst($palabra) {
    $newStr = '';
    $match = 0;
    foreach(str_split($palabra) as $k=> $letter) {
        if($match == 0 && preg_match('/^\p{L}*$/', $letter)){
            $newStr .= _ucwords($letter);
            break;
        }else{
            $newStr .= $letter;
        }
    }
    return $newStr.substr($palabra,$k+1);
}

function _ucwords($palabra) {
    return mb_convert_case(mb_strtolower($palabra, 'iso-8859-1'), MB_CASE_TITLE, 'iso-8859-1');
}

2 个答案:

答案 0 :(得分:1)

无聊:

<?php

$str="!34hi Fred hi";
$match=0;//no match yet
$newStr='';//output string
foreach(str_split($str) as $letter){ //split string for loop

if($match==0 && ctype_alpha($letter)){//check its a letter and its the first one we found
    $newStr.=strtoupper($letter);//upper case it and glue it
    $match=1;// set the match so we don't bother to check any more of the string

}else{
    $newStr .=$letter; //glue the rest of the string
}


}

echo $newStr; //!34Hi Fred hi

不要用于长字符串,最好在找到第一个匹配后打破循环,但是对于一个不重要的短字符串。

长字符串版本,效率更高,在第一次匹配时停止循环:

<?php


$str="!34hi Fred hi";
$newStr='';//output string

foreach(str_split($str) as $k=> $letter){ //split string for loop

if($match==0 && ctype_alpha($letter)){//check its a letter and its the first one we found
    $newStr.=strtoupper($letter);//upper case it and glue it
    break;//stop the foreach on first find, no need to keep looping
}else{
    $newStr .=$letter; //glue the non letters so far found it any
}


}
//add the rest of the sting back in
echo $newStr.substr($str,$k+1); //!34Hi Fred hi

答案 1 :(得分:0)

试试这个

  $a=strtolower("!34Hi Fred hi");
  $k=0;
  $b="";
  for($i=0;$i<strlen($a);$i++){
    if(ctype_alpha($a[$i])&&$k==0){
       $b.=strtoupper($a[$i]);
       $k=1;
    }else{
      $b.=$a[$i];
   }
}
echo $b;