web-dev-qa-db-fra.com

Convertir des tirets en CamelCase dans PHP

Quelqu'un peut-il m'aider à compléter cette fonction PHP? Je veux prendre une chaîne comme celle-ci: 'this-is-a-string' et la convertir en ceci: 'thisIsAString':

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


    return $string;
}
69
Kirk Ouimet

Aucune regex ou callbacks nécessaires. Presque tout le travail peut être fait avec 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');

Si vous utilisez PHP> = 5.3, vous pouvez utiliser lcfirst au lieu de strtolower.

Mettre à jour

Un deuxième paramètre a été ajouté à ucwords dans PHP 5.4.32/5.5.16, ce qui signifie que nous n'avons pas besoin de changer d'abord les tirets en espaces (merci à Lars Ebert et PeterM de l'avoir signalé). Voici le code mis à jour:

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

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

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

    return $str;
}

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

Ceci peut être fait très simplement, en utilisant ucwords qui accepte le délimiteur comme paramètre:

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

NOTE: Besoin de PHP au moins 5.4.32, 5.5.16

39
PeterM

c’est ma variante sur la façon de gérer cela. Ici, j'ai deux fonctions, premièrement une camelCase transforme n'importe quoi en camelCase et ne gâchera pas si la variable contient déjà cameCase. Second uncamelCase transforme camelCase en trait de soulignement (fonctionnalité intéressante pour les clés de base de données).

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;
}

permet de tester les deux:

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

J'utiliserais probablement preg_replace_callback() , comme ceci:

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

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

One-Liner surchargé, avec bloc de documentation ...

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

Vous recherchez preg_replace_callback , vous pouvez l'utiliser comme ceci:

$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
     return ucfirst($matches[1]);
}, $dashes);
4
Sparkup
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
    if( $first ) {
        $first = false;
        continue;
    }
    $v = ucfirst( $v );
}
return implode( "", $string );

Code non testé. Consultez la documentation PHP pour les fonctions im-/explode et ucfirst.

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

echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
2
Błażej Krzakala

Un liner, PHP> = 5.3:

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

La bibliothèque TurboCommons contient une méthode polyvalente formatCase () dans la classe StringUtils, qui vous permet de convertir une chaîne en un grand nombre de formats de cas usuels, tels que CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, etc.

https://github.com/edertone/TurboCommons

Pour l'utiliser, importez le fichier phar dans votre projet et:

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

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

// will output 'sNakeCase'

Voici le lien vers le code source de la méthode:

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

1
Jaume Mussons Abad

Sinon, si vous préférez ne pas vous occuper de regex et que vous voulez éviter les boucles explicit:

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

Essaye ça:

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

Sortie:

Snake_Case remove _ with str_replace
1
dılo sürücü

voici une solution très simple en code à une ligne 

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

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

sortie ThisIsAString 

1
Abbbas khan

Si vous utilisez le framework Laravel, vous pouvez utiliser simplement camel_case () method.

camel_case('this-is-a-string') // 'thisIsAString'
0
Marek Skiba

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

Le paramètre ucwords second (facultatif) aide à identifier un séparateur pour cameler la chaîne .str_replace est utilisé pour finaliser la sortie en supprimant le séparateur.

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

De toute évidence, si un autre délimiteur que '-', par ex. '_', doit également correspondre, alors cela ne fonctionnera pas, alors un preg_replace pourrait convertir tous les délimiteurs (consécutifs) en '-' dans $ text en premier ...

0
PeerGum

Voici une autre option:

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

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

    return implode('', $parts);
}
0

Cette fonction est similaire à la fonction de @ 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);
}

Mais plus clair, (je pense: D) et avec le paramètre optionnel pour capitaliser la première lettre ou non.

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"
0

Une autre approche simple:

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

Dans Laravel, utilisez Str::camel()

use Illuminate\Support\Str;

$converted = Str::camel('foo_bar');

// fooBar
0
Ronald Araújo