누군가가이 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');
$str = ! $capitalizeFirstCharacter ? lcfirst($str) : $str;주로 가독성 (일부는 동의하지 않을 수 있음) 및 / 또는 코드 복잡성 감소를 위해 삼항 연산자를 사용하여 다시 작성할 수 있습니다 .
이것은 구분자를 매개 변수로 받아들이는 ucwords 를 사용하여 매우 간단하게 수행 할 수 있습니다 .
function camelize($input, $separator = '_')
{
return str_replace($separator, '', ucwords($input, $separator));
}
참고 : 최소 5.4.32, 5.5.16 PHP가 필요합니다 .
return str_replace($separator, '', lcfirst(ucwords($input, $separator)));
ucwords두 번째 매개 변수 delimiter가 있으므로 str_replace("_", "", ucwords($input, "_"));충분합니다 (대부분의 경우 : P
이것은 그것을 다루는 방법에 대한 나의 변형입니다. 여기에 두 가지 함수가 있습니다. 첫 번째 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))));
}
null
return... 업데이트되었습니다. 다음은이 테스트 할 수있는 링크입니다 3v4l.org/YBHPd
나는 아마 다음 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';
또는 정규식을 처리하지 않고 명시 적 루프 를 피하려면 다음을 수행하십시오.
// $key = 'some-text', after transformation someText
$key = lcfirst(implode('', array_map(function ($key) {
return ucfirst($key);
}, explode('-', $key))));
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'
다음은 메소드 소스 코드에 대한 링크입니다.
이 시도:
$var='snake_case';
echo ucword($var,'_');
산출:
Snake_Case remove _ with str_replace
function camelCase($text) {
return array_reduce(
explode('-', strtolower($text)),
function ($carry, $value) {
$carry .= ucfirst($value);
return $carry;
},
'');
}
분명히, '-'이외의 다른 구분 기호 (예 : '_')도 일치하면 작동하지 않을 것입니다. 그러면 preg_replace는 먼저 $ text의 모든 구분 기호를 '-'로 변환 할 수 있습니다.
이 기능은 @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"
Laravel 프레임 워크를 사용하는 경우 camel_case () 메서드 만 사용할 수 있습니다 .
camel_case('this-is-a-string') // 'thisIsAString'
다음은 또 다른 옵션입니다.
private function camelcase($input, $separator = '-')
{
$array = explode($separator, $input);
$parts = array_map('ucwords', $array);
return implode('', $parts);
}
다음은 기능적 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);
}
);
}
위의 많은 좋은 솔루션이 있으며 이전에 아무도 언급하지 않은 다른 방법을 제공 할 수 있습니다. 이 예에서는 배열을 사용합니다. 내 프로젝트 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
이 시도:
return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
이것은 더 간단합니다.
$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );
if (!$capitalizeFirstCharacter) { $str = lcfirst($str); }