Computer >> 컴퓨터 >  >> 프로그래밍 >> PHP

PHP에서 대시(-)를 카멜케이스(CamelCase)로 변환하는 방법

PHP에서는 대시(-)로 구분된 문자열을 손쉽게 카멜케이스(CamelCase) 형태로 변환할 수 있습니다. 예를 들어 this-is-a-test-string과 같은 입력값을 thisIsATestString처럼 바꾸는 작업입니다.

입력 및 출력 예시

  • 입력: this-is-a-test-string
  • 출력: thisIsATestString

정규식 없이 간단하게 처리하기

이 변환에는 정규식(regex)이나 콜백 함수가 필요하지 않습니다. PHP의 기본 내장 함수인 ucwords만으로 충분히 구현할 수 있습니다. 아래 코드를 참고하세요.

function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
    $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
    if (!$capitalizeFirstCharacter) {
        $str[0] = strtolower($str[0]);
    }
    return $str;
}
echo dashToCamelCase('this-is-a-string');

위 코드는 먼저 대시(-)를 공백으로 치환한 뒤 ucwords로 각 단어의 첫 글자를 대문자로 만들고, 다시 공백을 제거하는 방식으로 동작합니다. 두 번째 매개변수인 $capitalizeFirstCharacter를 통해 첫 글자도 대문자로 시작할지 여부를 선택할 수 있습니다.

PHP 5.3 이상에서 사용하는 방법

PHP 5.3 이상 버전이라면 ucwords에 구분자(delimiter)를 직접 지정할 수 있어 더욱 간결한 코드 작성이 가능합니다.

function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
    $str = str_replace('-', '', ucwords($string, '-'));
    if (!$capitalizeFirstCharacter) {
        $str = lcfirst($str);
    }
    return $str;
}
echo dashToCamelCase('this-is-a-test-string');

lcfirst와 strtolower의 차이점

이 버전에서는 문자열의 첫 글자만 소문자로 변경해야 하기 때문에 전체 문자열에 영향을 주는 strtolower 대신 lcfirst 함수를 사용하는 것이 좋습니다. lcfirst는 이름 그대로 첫 번째 문자만 소문자로 바꿔주므로, 나머지 부분은 그대로 유지됩니다.

정리

대시로 구분된 문자열을 카멜케이스로 변환할 때는 정규식 없이 ucwords, str_replace, 그리고 필요에 따라 lcfirst를 조합하면 깔끔하고 효율적으로 해결할 수 있습니다.