字符串大小写转换(三种方法)


//直接通过转换比较;
function num1($str){
   $num = strlen($str);
   $res = '';
   for($i=0;$i<$num;$i++){
      if(strtolower($str[$i]) == $str[$i]){
         $res .= strtoupper($str[$i]);
      }else{
         $res .= strtolower($str[$i]);
      }
   }
   return $res;
}
echo num1($a);
echo "<hr/>";


//通过ASCII码值来判断;
function num2($str){
   $num = strlen($str);
   $res = '';
   for($i=0;$i<$num;$i++){
      $n = ord($str[$i]);
      if($n<=122 && $n>=97){
         $n = $n-32;
      }else{
         $n = $n+32;
      }
      $res .= chr($n);
   }
   return $res;
}
echo num2($a);
echo "<hr/>";


//直接生成两个数组(大写、小写),再放进去循环比较,如果是在小写或者大写的数组内比较到相同的就转换;
function num3($str){
   $a = range('a','z');
   $b = range('A','Z');
   $num = strlen($str);
   $res = '';
   for($i=0;$i<$num;$i++){
      if(in_array($str[$i],$a)){
         foreach ($a as $key => $value) {
            if($value == $str[$i]){
               $tmp = $key;
            }
         }
         $res .= $b[$tmp];
      }
      if(in_array($str[$i],$b)){
         foreach ($b as $key => $value) {
            if($value == $str[$i]){
               $tmp = $key;
            }
         }
         $res .= $a[$tmp];
      }
   }
  return $res; } echo num3($a);
原文地址:https://www.cnblogs.com/jacko/p/4827505.html