707   PHP

一,使用系统函数

$str= 'as,d中文SD;f';

var_dump($str);
// 根据字符串编码方式转换,避免了中文乱码
var_dump(mb_strtoupper($str, mb_detect_encoding($str, array("ASCII","UTF-8","EUC-CN","GB2312","GBK","BIG5"))));
var_dump(mb_strtolower($str, mb_detect_encoding($str, array("ASCII","UTF-8","EUC-CN","GB2312","GBK","BIG5"))));

二,为了避免中文乱码,通过ASCII码实现转换

$str= 'as,d中文SD;f';

function strToUp($str){
        // 把字符串按字节分割
	$arr= str_split($str);
	$new_str='';
	foreach ($arr as $key => $val) {
                // 获取字节的ASCII码
		$acc=ord($val);
                // 是否在a(97)到z(122)之间
		if($acc>=97&&$acc<=122){ // 转化为大写,大写比小写的ASCII码小32 $acc=$acc-32; } // 将ASCII码变为字符串 $new_str.=chr($acc); } return $new_str; } function strToLow($str){ // 把字符串按字节分割 $arr= str_split($str); $new_str=''; foreach ($arr as $key => $val) {
                // 获取字节的ASCII码
		$acc=ord($val);
                // 是否在A(65)到Z(90)之间
		if($acc>=65&&$acc<=90){
                        // 转化为小写,小写比大写的ASCII码大32
			$acc=$acc+32;
		}
                // 将ASCII码变为字符串
		$new_str.=chr($acc);
	}
	return $new_str;	
}

var_dump($str);
var_dump(strToUp($str));
var_dump(strToLow($str));



Leave a Reply

Your email address will not be published. Required fields are marked *