본문 바로가기

PHP

UTF-8 기준, 한글을 초성,중성,종성으로 분리하기

<?php
function GetUtf8String($str) {
	$arr_cho = array("ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ","ㅂ", "ㅃ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ","ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ");
	$arr_jung = array("ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ","ㅖ", "ㅗ", "ㅘ", "ㅙ", "ㅚ", "ㅛ", "ㅜ","ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ", "ㅣ");
	$arr_jong = array("", "ㄱ", "ㄲ", "ㄳ", "ㄴ", "ㄵ", "ㄶ","ㄷ", "ㄹ", "ㄺ", "ㄻ", "ㄼ", "ㄽ", "ㄾ","ㄿ", "ㅀ", "ㅁ", "ㅂ", "ㅄ", "ㅅ", "ㅆ","ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ");

	$unicode = array();
	$values = array();
	$lookingFor = 1;

	for ($i=0, $loop=strlen($str);$i<$loop;$i++) {
		$thisValue = ord($str[$i]);

		if ($thisValue < 128) {
			$unicode[] = $thisValue;
		} else {
			if (count($values) == 0) $lookingFor = $thisValue < 224 ? 2 : 3;
			$values[] = $thisValue;

			if (count($values) == $lookingFor) {
				$number = $lookingFor == 3 ? (($values[0]%16)*4096)+(($values[1]%64)*64)+($values[2]%64) : (($values[0]%32)*64)+($values[1]%64);
				$unicode[] = $number;
				$values = array();
				$lookingFor = 1;
			}
		}
	}

	$splitStr = '';
	while (list($key,$code) = each($unicode)) {
		if ($code >= 44032 && $code <= 55203) {
			$temp = $code-44032;

			$cho = (int)($temp/21/28);
			$jung = (int)(($temp%(21*28)/28));
			$jong = (int)($temp%28);

			$splitStr.= $arr_cho[$cho].$arr_jung[$jung].$arr_jong[$jong];
		} else {
			$temp = array($unicode[$key]);

			foreach ($temp as $ununicode) {
				if ($ununicode < 128) {
					$splitStr.= chr($ununicode);
				} elseif ($ununicode < 2048) {
					$splitStr.= chr(192+(($ununicode-($ununicode%64))/64));
					$splitStr.= chr(128+($ununicode%64));
				} else {
					$splitStr.= chr(224+(($ununicode-($ununicode%4096))/4096));
					$splitStr.= chr(128+((($ununicode%4096)-($ununicode%64))/64));
					$splitStr.= chr(128+($ununicode%64));
				}
			}
		}
	}
	$splitStr = str_replace(' ','',$splitStr);

	return $splitStr;
}

// UTF-8 문자열 생성
$str = iconv('euc-kr','utf-8','알쯔\'s 외부기억장치');

echo GetUtf8String($str);
// return ㅇㅏㄹㅉㅡ'sㅇㅚㅂㅜㄱㅣㅇㅓㄱ ㅈㅏㅇㅊㅣ(http://blog.arzz.com)
?>

출처 : http://blog.arzz.com/192



// 추가내용

$str = iconv('euc-kr','utf-8',$string); $string = GetUtf8String($str); $firstword = ord( substr( $string, 0, 1 ) );

if (127 > $firstword) { $string = substr($string, 0, 1); } else { if(227 == $firstword) { $string = iconv('utf-8','euc-kr',$string); } $string = substr($string, 0, 2); }


// 맨 앞글자의 초성만 가져온다.