[php] PHP에서 대시를 CamelCase로 변환

누군가가이 PHP 기능을 완료하도록 도울 수 있습니까? ‘this-is-a-string’과 같은 문자열을 가져 와서 다음과 같이 변환합니다. ‘thisIsAString’:

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
    // Do stuff


    return $string;
}



답변

정규식이나 콜백이 필요하지 않습니다. 거의 모든 작업을 ucwords로 수행 할 수 있습니다.

function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{

    $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));

    if (!$capitalizeFirstCharacter) {
        $str[0] = strtolower($str[0]);
    }

    return $str;
}

echo dashesToCamelCase('this-is-a-string');

PHP> = 5.3을 사용하는 경우 strtolower 대신 lcfirst를 사용할 수 있습니다.

최신 정보

두 번째 매개 변수가 PHP 5.4.32 / 5.5.16의 ucwords에 추가되었습니다. 즉, 먼저 대시를 공백으로 변경할 필요가 없습니다 (이 점을 지적한 Lars Ebert와 PeterM에게 감사드립니다). 다음은 업데이트 된 코드입니다.

function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{

    $str = str_replace('-', '', ucwords($string, '-'));

    if (!$capitalizeFirstCharacter) {
        $str = lcfirst($str);
    }

    return $str;
}

echo dashesToCamelCase('this-is-a-string');


답변

이것은 구분자를 매개 변수로 받아들이는 ucwords 를 사용하여 매우 간단하게 수행 할 수 있습니다 .

function camelize($input, $separator = '_')
{
    return str_replace($separator, '', ucwords($input, $separator));
}

참고 : 최소 5.4.32, 5.5.16 PHP가 필요합니다 .


답변

이것은 그것을 다루는 방법에 대한 나의 변형입니다. 여기에 두 가지 함수가 있습니다. 첫 번째 camelCase 는 모든 것을 camelCase로 바꾸고 변수에 이미 cameCase가 포함되어 있으면 엉망이되지 않습니다. 두 번째 uncamelCase 는 camelCase를 밑줄로 바꿉니다 (데이터베이스 키를 다룰 때 훌륭한 기능).

function camelCase($str) {
    $i = array("-","_");
    $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
    $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
    $str = str_replace($i, ' ', $str);
    $str = str_replace(' ', '', ucwords(strtolower($str)));
    $str = strtolower(substr($str,0,1)).substr($str,1);
    return $str;
}
function uncamelCase($str) {
    $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
    $str = strtolower($str);
    return $str;
}

둘 다 테스트 해 보겠습니다.

$camel = camelCase("James_LIKES-camelCase");
$uncamel = uncamelCase($camel);
echo $camel." ".$uncamel;


답변

문서 블록이있는 오버로드 된 한 줄짜리 …

/**
 * Convert underscore_strings to camelCase (medial capitals).
 *
 * @param {string} $str
 *
 * @return {string}
 */
function snakeToCamel ($str) {
  // Remove underscores, capitalize words, squash, lowercase first.
  return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}


답변

나는 아마 다음 preg_replace_callback()과 같이 사용할 것입니다 .

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
  return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
}

function removeDashAndCapitalize($matches) {
  return strtoupper($matches[0][1]);
}


답변

preg_replace_callback을 찾고 있습니다. 다음과 같이 사용할 수 있습니다.

$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
     return ucfirst($matches[1]);
}, $dashes);


답변

function camelize($input, $separator = '_')
{
    return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}

echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';