PHP에서 대시를 CamelCase로 변환


91

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

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


    return $string;
}

답변:


184

정규식이나 콜백이 필요하지 않습니다. 거의 모든 작업을 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');

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

3
참고 ucwords실제로 두 번째 매개 변수 (참조로 구분 기호를 받아들이는 peterm는 의해 답변을 ), 그래서 하나 str_replace호출은 불필요 할 것이다.
Lars Ebert

정보 @LarsEbert에 감사드립니다. 답변을 업데이트했습니다.
webbiedave

조건은 $str = ! $capitalizeFirstCharacter ? lcfirst($str) : $str;주로 가독성 (일부는 동의하지 않을 수 있음) 및 / 또는 코드 복잡성 감소를 위해 삼항 연산자를 사용하여 다시 작성할 수 있습니다 .
Chris Athanasiadis

54

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

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

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


33
당신이 원하는 경우에이 CamelCase를 같은 수 : -이 낙타 표기법처럼 뭔가를 반환합니다return str_replace($separator, '', lcfirst(ucwords($input, $separator)));
제프 S.

ucwords두 번째 매개 변수 delimiter가 있으므로 str_replace("_", "", ucwords($input, "_"));충분합니다 (대부분의 경우 : P
wbswjc

8

이것은 그것을 다루는 방법에 대한 나의 변형입니다. 여기에 두 가지 함수가 있습니다. 첫 번째 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;

이 기능을 대신 jamesLikesCameCase의 낙타 표기법에 대한 jamesLikesCameAse을 반환
ALARI Truuts

8

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

/**
 * 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))));
}

이것은 반환 될 것입니다null
PeterM

기능이 부족했습니다 return... 업데이트되었습니다. 다음은이 테스트 할 수있는 링크입니다 3v4l.org/YBHPd
doublejosh

6
진정해 친구, 방금 반환을 놓쳤습니다. 그래서 긍정적 인 태도를 유지하십시오.
doublejosh

5

나는 아마 다음 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]);
}

4

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

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

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

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

3
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
    if( $first ) {
        $first = false;
        continue;
    }
    $v = ucfirst( $v );
}
return implode( "", $string );

테스트되지 않은 코드. im- / explode 및 ucfirst 함수에 대한 PHP 문서를 확인하십시오.


3

라이너 1 개, PHP> = 5.3 :

$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));

1
이 캔 / 영업 도움이 될 것입니다 방법을 몇 가지 설명을 추가하십시오
davejal

2

여기 한 줄 코드로 매우 쉬운 솔루션이 있습니다.

    $string='this-is-a-string' ;

   echo   str_replace('-', '', ucwords($string, "-"));

ThisIsAString 출력


1

또는 정규식을 처리하지 않고 명시 적 루프 를 피하려면 다음을 수행하십시오.

// $key = 'some-text', after transformation someText            
$key = lcfirst(implode('', array_map(function ($key) {
    return ucfirst($key);
}, explode('-', $key))));

1

또 다른 간단한 접근 방식 :

$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));

1

TurboCommons 라이브러리에는 StringUtils 클래스 내에 범용 formatCase () 메서드가 포함되어있어 문자열을 CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case 등과 같은 많은 일반적인 케이스 형식으로 변환 할 수 있습니다.

https://github.com/edertone/TurboCommons

이를 사용하려면 phar 파일을 프로젝트로 가져오고 다음을 수행하십시오.

use org\turbocommons\src\main\php\utils\StringUtils;

echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);

// will output 'sNakeCase'

다음은 메소드 소스 코드에 대한 링크입니다.

https://github.com/edertone/TurboCommons/blob/b2e015cf89c8dbe372a5f5515e7d9763f45eba76/TurboCommons-Php/src/main/php/utils/StringUtils.php#L653


1

이 시도:

$var='snake_case';
echo ucword($var,'_');

산출:

Snake_Case remove _ with str_replace


0
function camelCase($text) {
    return array_reduce(
         explode('-', strtolower($text)),
         function ($carry, $value) {
             $carry .= ucfirst($value);
             return $carry;
         },
         '');
}

분명히, '-'이외의 다른 구분 기호 (예 : '_')도 일치하면 작동하지 않을 것입니다. 그러면 preg_replace는 먼저 $ text의 모든 구분 기호를 '-'로 변환 할 수 있습니다.


약 4 년 전에 제공된 (및 수용된) 솔루션보다 이것이 얼마나 더 간단하고, 명확하며, 더 나은지 알 수 없습니다.
ccjmne 2014-08-29

0

이 기능은 @Svens의 기능과 유사합니다.

function toCamelCase($str, $first_letter = false) {
    $arr = explode('-', $str);
    foreach ($arr as $key => $value) {
        $cond = $key > 0 || $first_letter;
        $arr[$key] = $cond ? ucfirst($value) : $value;
    }
    return implode('', $arr);
}

그러나 더 명확하고 (나는 : D라고 생각합니다) 첫 글자를 대문자로 사용하거나 사용하지 않는 선택적 매개 변수를 사용합니다.

용법:

$dashes = 'function-test-camel-case';
$ex1 = toCamelCase($dashes);
$ex2 = toCamelCase($dashes, true);

var_dump($ex1);
//string(21) "functionTestCamelCase"
var_dump($ex2);
//string(21) "FunctionTestCamelCase"


0

다음은 또 다른 옵션입니다.

private function camelcase($input, $separator = '-')     
{
    $array = explode($separator, $input);

    $parts = array_map('ucwords', $array);

    return implode('', $parts);
}

0

$stringWithDash = 'Pending-Seller-Confirmation'; $camelize = str_replace('-', '', ucwords($stringWithDash, '-')); echo $camelize; 출력 : PendingSellerConfirmation

ucwordssecond (선택적) 매개 변수는 문자열을 낙타 화하기위한 구분 기호를 식별하는 데 도움이됩니다. str_replace구분 기호를 제거하여 출력을 마무리하는 데 사용됩니다.


0

다음은 기능적 array_reduce 접근 방식을 사용하는 작은 도우미 함수 입니다. PHP 7.0 이상 필요

private function toCamelCase(string $stringToTransform, string $delimiter = '_'): string
{
    return array_reduce(
        explode($delimiter, $stringToTransform),
        function ($carry, string $part): string {
            return $carry === null ? $part: $carry . ucfirst($part);
        }
    );
}

0

위의 많은 좋은 솔루션이 있으며 이전에 아무도 언급하지 않은 다른 방법을 제공 할 수 있습니다. 이 예에서는 배열을 사용합니다. 내 프로젝트 Shieldon Firewall 에서이 방법을 사용합니다 .

/**
 * Covert string with dashes into camel-case string.
 *
 * @param string $string A string with dashes.
 *
 * @return string
 */
function getCamelCase(string $string = '')
{
    $str = explode('-', $string);
    $str = implode('', array_map(function($word) {
        return ucwords($word); 
    }, $str));

    return $str;
}

테스트 :

echo getCamelCase('This-is-example');

결과:

ThisIsExample


-2

이것은 더 간단합니다.

$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );

/ e 수정자는 PHP 5.5에서 더 이상 사용되지 않습니다.
Ondrej Machulda 2013
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.