변환 및 제거
- trim, ltrim, chop (문자열 정리)
$result = trim($string) // 앞뒤 공백문자 제거
$result = ltrim($string) // 앞 공백문자 제거
$result = chop($string) // 뒤 공백문자 제거
- strtoupper, strtolower, ucfirst, ucword(대소문자 정리)
$result = strtoupper($string) - 문자열을 모두 대문자로 변환
$result = strtolower($string) - 문자열을 모두 소문자로 변환
$result = ucfirst($string) - 문자열의 첫단어가 영문자이면 그것만 대문자로 변환
$result = ucword($string) - 문자열 각단어의 첫 영문자를 대문자로 변환
- str_replace(“찾을 문자”, “변경할 문자”, “대상 문자열”)
$val = "he is programmer";
$val = str_replace("he", "she", $val);
print_r($val);
>>> she is programmer
- substr_replace(“대상 문자열”, “변경할 문자”, 위치, “변환할 문자열 수”)
$val = "ABCDEFG";
$val = substr_replace($val, "2", 2); // 인덱스 위치 2부터 모두 제거 후 변환될 문자열 삽입
print_r($val);
>>> AB2
$val = "ABCDEFG";
$val = substr_replace($val, "2", 2, 0); // 인덱스 위치 2부터 변환될 문자열 삽입
print_r($val);
>>> AB2CDEFG
$val = "ABCDEFG";
$val = substr_replace($val, "2", 2, 2); // 인덱스 위치 2부터 2개의 문자열 제거 후 변환될 문자열 삽입
print_r($val);
>>> AB2EFG
- preg_replace(“/찾을 문자/”, “변경할 문자”, “대상 문자열”) – 정규표현식 사용 가능
$val = "excel A1 column update";
$val = preg_replace("/[0-9]/", "A9", $val);
print_r($val);
>>> excel AA9 column update
$str = "he is programmer";
$val[0] = "he";
$val[1] = "programmer";
$replace[0] = "she";
$replace[1] = "designer";
$str = str_replace($val, $replace, $str);
print_r($str);
>> she is designer
기타 ( 자르기, 찾기, 비교, 길이 )
- substr($원본문자열, $찾을위치, $갯수) – 문자열 자르기
$str = "he is programmer";
print_r(substr($str, 5));
// 인덱스 5번부터
print_r(substr($str, 5, 4)); // 인덱스 5번부터 4개
print_r(substr($str, 5, -2)); // 인덱스 5번부터 인덱스 -2번 전까지
- strpos($원본문자열, $찾을문자열) – 문자열 찾기
$result = strpos("hello","lo");
print_r($result); // 해당 위치의 인덱스 반환, 없다면 false
- strcmp($비교문자열1, $비교문자열2) – 문자열 비교
$result = strcmp($str1,$str2);
print_r($result);
// 같다면 0, ASCII 코드값이 str1이 더 크다면 양수, str2가 더 크다면 음수
strcasecmp - 대소문자 구분 X
print_r(strlen("hello"));
>>> 5
- empty – 배열이 비어있거나 값이 0 또는 FALSE인지 체크
# 결과 empty
$test = 0;
$test = array();
$test = FALSE;
if(empty($test)) {
echo "empty";
}else{
echo "not empty";
}
# 결과 is_numeric
$test = "12345";
$test = 12345;
# 결과 not is_numeric
$test = "adaagsd";
if(is_numeric($test)) {
print "is_numeric";
}else{
print "not is_numeric";
}