길이(byte)에 따라 문자열 자르기(javascript)

function cutStr(str,limit){
var tmpStr = str;
var byte_count = 0;
var len = str.length;
var dot = “”;

for(i=0; i byte_count += chr_byte(str.charAt(i));
if(byte_count == limit-1){
if(chr_byte(str.charAt(i+1)) == 2){
tmpStr = str.substring(0,i+1);
dot = “…”;
}else {
if(i+2 != len) dot = “…”;
tmpStr = str.substring(0,i+2);
}
break;
}else if(byte_count == limit){
if(i+1 != len) dot = “…”;
tmpStr = str.substring(0,i+1);
break;
}
}
document.writeln(tmpStr+dot);
return true;
}
function chr_byte(chr){
if(escape(chr).length > 4)
return 2;
else
return 1;
}

실제로 쓰이는 함수는 cutStr(str,limit)입니다.
본문에 와 같이 삽입해주시면 됩니다. 예제는 30byte로 자른 거구요.
바이트 단위로 했을 때 2byte문자(한글같은…)가 잘리게 된다면 글자 잘림을 방지하기 위해 출력 길이를 1byte줄여서 출력합니다. chr_byte 함수는 입력된 글자가 1byte인지 2byte인지 체크하는 기능을 합니다

순번 매기기

프로그램을 하다보면 아래와 같이 파일등에 순번을 매기는 경우가 있습니다.
1
2
… 중략
9
10
11

그런데 탐색기에서는 아래와 같이 표시가 되지요

1
10
11
2
.. 중략 …
9

다음과 같은 방법으로 매기면 편리합니다.

for($i=1; $i<=1000; $i++) {
$num = substr(“0000” . $i , -4); // 뒤에서 부터 4자리 만큼
}

그러면 $num 값이

0001
0002
0003
… 중략 …
0999
1000

이런식으로 매겨지므로 탐색기등에서도 제대로 출력됩니다.

[끝]

북극곰 $num = sprintf(“%04d”, $i);

석봉운님의 라이브러리

석봉운
http://www.mytechnic.com

# 잘 쓰세요..
# 해피 추석입니다.
# 자바스크립트 라이브러리와 PHP함수 라이브러리를 같이 올립니다.
# 일부는 PHP스쿨에서 발췌하여 만든 소스입니다.

//셀렉트
function optionlist($optionlist, $getvalue=””, $keyfield=”key”, $valuefield=”value”) {
foreach($optionlist as $key => $value) {
if($getvalue && $getvalue == ${$keyfield}) $chk = “selected”;
else $chk = “”;
echo ““;
}
echo “
“;
}

//셀렉티드
function selected($checkkey, $getvalue=””) {
echo “value=’$checkkey'”;
if($getvalue && $checkkey == $getvalue) echo ” selected”;
}

//체크드
function checked($checkkey, $getvalue=””) {
echo “value=’$getvalue'”;
if($getvalue && $checkkey == $getvalue) echo ” checked”;
}

//주민번호 검사
function RegiNum($reginum) {
$weight = ‘234567892345’; // 자리수 weight 지정
$len = strlen($reginum);
$sum = 0;

if ($len <> 13) { return false; }

for ($i = 0; $i < 12; $i++) {
$sum = $sum + (substr($reginum,$i,1) * substr($weight,$i,1));
}

$rst = $sum%11;
$result = 11 – $rst;

if ($result == 10) {$result = 0;}
else if ($result == 11) {$result = 1;}

$jumin = substr($reginum,12,1);

if ($result <> $jumin) {return false;}
return true;
}

//사업자번호 검사
function comRegiNum($reginum) {
$weight = ‘137137135’; // 자리수 weight 지정
$len = strlen($reginum);
$sum = 0;

if ($len <> 10) { return false; }

for ($i = 0; $i < 9; $i++) {
$sum = $sum + (substr($reginum,$i,1) * substr($weight,$i,1));
}
$sum = $sum + ((substr($reginum,8,1)*5)/10);
$rst = $sum%10;

if ($rst == 0) {$result = 0;}
else {$result = 10 – $rst;}

$saub = substr($reginum,9,1);

if ($result <> $saub) {return false;}
return true;
}

//글자르기
function cut_str($msg,$cut_size,$tail=”…”) {
if($cut_size <= 0) return $msg;
$msg = strip_tags($msg);
$msg = str_replace(“∓quot;”,”””,$msg);
if(strlen($msg) <= $cut_size) return $msg; for($i=0;$i<$cut_size;$i++) if(ord($msg[$i])>127) $han++; else $eng++;
if($han%2) $han–;

$cut_size = $han + $eng;

$tmp = substr($msg,0,$cut_size);
$tmp .= $tail;
return $tmp;
}

// 모든한글의 글자를 출력
function hangul_code() {
$count = 0;
for($i = 0x81; $i <= 0xC8; $i++) {
for($j = 0x00; $j <= 0xFE; $j++) {
if(($j >= 0x00 && $j <= 0x40) || ($j >= 0x5B && $j <= 0x60) || ($j >= 0x7B && $j <= 0x80) || ($j >= 0x00 && $j <= 0x40) ||
(($i >= 0xA1 && $i <=0xAF) && ($j >= 0xA1 && $j <= 0xFE)) || ($i == 0xC6 && ($j >= 0x53 && $j <= 0xA0)) ||
($i >= 0xC7 && ($j >= 0x41 && $j <= 0xA0))) continue;
echo chr($i).chr($j).” “;
$count++;
}
}
echo $count;
}

// 한글검사
function is_han($str) {
if(strlen($str) != 2) return false;

$i = ord ($str[0]);
$j = ord ($str[1]);

if($i < 0x81 || $i > 0xC8 || $j > 0xFE || ($j >= 0x00 && $j <= 0x40) || ($j >= 0x5B && $j <= 0x60) || ($j >= 0x7B && $j <= 0x80) ||
($j >= 0x00 && $j <= 0x40) || (($i >= 0xA1 && $i <=0xAF) && ($j >= 0xA1 && $j <= 0xFE)) ||
($i == 0xC6 && ($j >= 0x53 && $j <= 0xA0)) || ($i >= 0xC7 && ($j >= 0x41 && $j <= 0xA0))) return false;
else return true;
}

// 랜덤값 생성
function random_string($length) {
$randomcode = array(‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘0’,
‘A’, ‘B’, ‘C’, ‘d’, ‘E’, ‘F’, ‘G’, ‘H’, ‘x’, ‘J’,
‘K’, ‘b’, ‘M’, ‘N’, ‘y’, ‘P’, ‘r’, ‘R’, ‘S’, ‘T’,
‘u’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’);
mt_srand((double)microtime()*1000000);
for($i=1;$i<=$length;$i++) $Rstring .= $randomcode[mt_rand(1, 36)];
return $Rstring;
}

// 디렉토리 리스트
function DirList($path=”./”) {
$path = opendir($path);
while($list = readdir($path)) if($list != “.” && $list != “..”) $Arraydir[] = $list;
closedir($path);
return $Arraydir;
}

// 15자리의 유일한 숫자값 만들기
function uniquenumber() {
$temparray = explode(” “, microtime());
$temparray2 = substr($temparray[0],2,5);
$number =$temparray[1].$temparray2;
return $number;
}

// 파일이름과 확장자 분리
function ExplodeFile($filename) {
$filename = strtolower($filename);
$elements = explode(‘.’,$filename);
$elemcnt = count($elements)-1;
if(count($elements)==1) $ext = ”;
else $ext = $elements[$elemcnt];
unset($elements[$elemcnt]);
$fname = implode($elements,”);

$fileinfo[“name”] = $fname;
$fileinfo[“ext”] = $ext;
return $fileinfo;
}

// 그림확장자
function ImageType($filename) {
$webimg = explodefile($filename);

$webext = $webimg[“ext”];
$defineexp = array(“gif”,”jpg”,”png”);

$count = count($defineexp);

for($i=0;$i<$count;$i++) {
if($defineexp[$i] == $webext) return true;
}
return false;
}

// 유닉스날짜 포맷
function date_format($unixtime,$format=”Y.m.d”,$empty=” “) {
if($unixtime) return date($format, $unixtime);
else return $empty;
}

//YYYY-MM-DD 형식을 유닉스 타임으로
function unix_format($times, $operator=”-“, $type=true) {
if($type == true) {
$times = trim($times);
$arry = explode($operator,$times);
if(count($arry) != 3) return date_format(0);
$mktime = mktime(0,0,0,$arry[1],$arry[2],$arry[0]);
return date(“U”, $mktime);
} else {
$formats = “Y{$operator}m{$operator}d”;
return date($formats, $times);
}
}

// 주민등록번호 포맷
function jumin_format($juminno, $cutno=3, $des=”x”, $empty=” “) {
$juminno = str_replace(“-“,””,$juminno);
if(strlen($juminno) != 13) return $empty;
for($i=0;$i<$cutno;$i++) $x .= $des;
$juminno = substr($juminno,0,13-$cutno).$x;
$juminno = substr($juminno,0,6).”-“.substr($juminno,6);
return $juminno;
}

// 홈페이지 포맷
function url_format($url, $ltype=false, $title=false, $other=””, $htype=”http://”, $empty=” “) {
$url = eregi_replace(“http://”,””,trim($url));
if($url) $url = $htype.$url;
else return $empty;

if($title) $turl = $title;
else $turl = $url;

if($ltype) return “{$turl}“;
else return $url;
}

// 전송값 초기화
function post_format($str, $type) {
switch($type) {
case “url”:
$str = trim($str);
$str = eregi_replace(“http://”,””,$str);
break;
case “num”:
$str = trim($str);
$str = str_replace(“,”,””,$str);
break;
}
return $str;
}

// 이메일 포맷
function mail_format($email, $ltype=false, $title=false, $empty=” “) {
$email = trim($email);
$title = trim($title);

if(!$email && !$title) return $empty;
else if(!$email) return $title;

if($title) $temail = $title;
else $temail = $email;

if($ltype) return “{$temail}“;
else return $email;
}

// 전화번호 포맷
function tel_format($num1, $num2, $num3, $format=”-“, $empty=” “) {
$num1 = trim($num1);
$num2 = trim($num2);
$num3 = trim($num3);

if(!$num1) $num1 = “02”;

if($num2 && $num3) return $num1.$format.$num2.$format.$num3;
else return $empty;
}

// 문자 포맷
function text_format($str, $empty=” “) {
$str = trim($str);
if($str) return $str;
else return $empty;
}

// 새창띄우기
function win_format($title, $url, $target, $width, $height, $scrollbars=1, $empty) {
$title = text_format($title, $empty);
return “{$title}“;
}

// 나이(주민등록번호를 이용)
function AGE_jumin($lno,$rno) {
$refArray = Array(18,19,19,20,20,16,16,17,17,18);
$refyy = substr($rno,0,1);

$biryear = $refArray[$refyy] * 100 + substr($lno,0,2);
$nowyear = date(“Y”);
return $nowyear – $biryear + 1;
}

// URL 존재확인
function URL_exists($url) {
$url = str_replace(“http://”, “”, $url);
list($domain, $file) = explode(“/”, $url, 2); // 도메인부분과 주소부분으로 나눕니다.
$fid = fsockopen($domain, 80); // 도메인을 오픈합니다.
fputs($fid, “GET /$file HTTP/1.0
Host: $domain

“); // 파일 정보를 얻습니다.
$gets = fgets($fid, 128);
fclose($fid);

if(ereg(“200 OK”, $gets)) return TRUE;
else return FALSE;
}

// 조사 꾸미기
$array = “뵤 벼 뱌 배 베 보 버 바 비 뷰 부 브

숫자를 문자로 바꾸기 1234=>일천이백삼십사

이 함수의 사용목적은
1,223,445 => 일백이십이만삼천사백사십오
와 같은 문자로 바꾸어 주는 것인데

다른 소스도 있는것 같았지만
정수에 대해서만 처리를 하다보니 자료형 한도값에 걸리는 소스뿐이어서
저에겐 사용 불능이었다는…

일단 문자형으로 숫자들을 입력넣으면 에러 없이 돌아값니다.
뭐 작은 일억 정도의 작은 수는 정수형으로도 상관 없구요

소수점을 읽는 부분은 저한테 필요가 없어서…생략…
그럼…

##########################################################
## numtotext함수 ##
## infomation to use ##
## 숫자를 한글로 바꾸기 위한 함수 ##
## first Written 2002-03-26 ##
##########################################################

function numtotext($num) {
//선언
$text =”;

$dot_symbol = array(
‘4’ => “만”,
‘8’ => “억”,
’12’ => “조”,
’16’ => “경”,
’20’ => “해”,
’24’ => “시”,
’28’ => “양”,
’32’ => “구”,
’36’ => “간”,
’40’ => “정”,
’44’ => “재”,
’48’ => “극”,
’52’ => “항하사”,
’56’ => “아승지”,
’60’ => “나유타”,
’64’ => “불가사의”,
’68’ => “무량대수”
);

$power_symbol = array(
‘0’ => “”,
‘1’ => “십”,
‘2’ => “백”,
‘3’ => “천”
);

$text_symbol = array(
‘0’ => “”,
‘1’ => “일”,
‘2’ => “이”,
‘3’ => “삼”,
‘4’ => “사”,
‘5’ => “오”,
‘6’ => “육”,
‘7’ => “칠”,
‘8’ => “팔”,
‘9’ => “구”
);
//음수 여부 확인
if(substr($num,0,1) == ‘-‘) {
$num = substr($num ,1);
$text .= ‘마이너스’;
}
//전체 자리수 확인
$length_of_num = strlen($num);
//숫자 표현 여부 확인
if($length_of_num > 72) {
$text = “존재할 수 없는 수치 입니다.”;
}else{ ####0000
//실행
for ($k=0; $k< $length_of_num; $k++) {
$striped_value = substr($num, $k, 1);

$text .= $text_symbol[$striped_value];

$power_value = ($length_of_num – $k -1)%4;
if ($striped_value <> 0)
$text .= $power_symbol[$power_value];

if ($power_value == 0)
$text .= $dot_symbol[$length_of_num – $k -1];
}

} ####0000
return $text;
}
?>