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);
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
if( $first ) {
$first = false;
continue;
}
$v = ucfirst( $v );
}
return implode( "", $string );
테스트되지 않은 코드. im- / explode 및 ucfirst 함수에 대한 PHP 문서를 확인하십시오.
function camelize($input, $separator = '_')
{
return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}
echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
라이너 1 개, PHP> = 5.3 :
$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));
또는 정규식을 처리하지 않고 명시 적 루프 를 피하려면 다음을 수행하십시오.
// $key = 'some-text', after transformation someText
$key = lcfirst(implode('', array_map(function ($key) {
return ucfirst($key);
}, explode('-', $key))));
여기 한 줄 코드로 매우 쉬운 솔루션이 있습니다.
$string='this-is-a-string' ;
echo str_replace('-', '', ucwords($string, "-"));
ThisIsAString 출력
The TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.
https://github.com/edertone/TurboCommons
To use it, import the phar file to your project and:
use org\turbocommons\src\main\php\utils\StringUtils;
echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);
// will output 'sNakeCase'
Here's the link to the method source code:
Try this:
$var='snake_case';
echo ucword($var,'_');
Output:
Snake_Case remove _ with str_replace
function camelCase($text) {
return array_reduce(
explode('-', strtolower($text)),
function ($carry, $value) {
$carry .= ucfirst($value);
return $carry;
},
'');
}
Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...
This function is similar to @Svens's function
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);
}
But clearer, (i think :D) and with the optional parameter to capitalize the first letter or not.
Usage:
$dashes = 'function-test-camel-case';
$ex1 = toCamelCase($dashes);
$ex2 = toCamelCase($dashes, true);
var_dump($ex1);
//string(21) "functionTestCamelCase"
var_dump($ex2);
//string(21) "FunctionTestCamelCase"
Another simple approach:
$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));
If you use Laravel framework, you can use just camel_case() method.
camel_case('this-is-a-string') // 'thisIsAString'
Here is another option:
private function camelcase($input, $separator = '-')
{
$array = explode($separator, $input);
$parts = array_map('ucwords', $array);
return implode('', $parts);
}
$stringWithDash = 'Pending-Seller-Confirmation'; $camelize = str_replace('-', '', ucwords($stringWithDash, '-')); echo $camelize;
output: PendingSellerConfirmation
ucwords
second(optional) parameter helps in identify a separator to camelize the string. str_replace
is used to finalize the output by removing the separator.
In Laravel use Str::camel()
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar
Here is a small helper function using a functional array_reduce approach. Requires at least 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);
}
);
}
Try this:
return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
This is simpler :
$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );
참고URL : https://stackoverflow.com/questions/2791998/convert-dashes-to-camelcase-in-php
'programing' 카테고리의 다른 글
엔티티 이름은 엔티티 참조에서 '&'바로 뒤에 와야합니다. (0) | 2020.10.20 |
---|---|
SQL 네트워크 인터페이스, 오류 : 50-로컬 데이터베이스 런타임 오류가 발생했습니다. (0) | 2020.10.20 |
C 프로그래밍에서 대? (0) | 2020.10.20 |
바탕 화면 바로 가기에서 명령 프롬프트 명령 실행 (0) | 2020.10.20 |
JObject로 즉석에서 JSON 만들기 (0) | 2020.10.20 |