Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created December 22, 2010 13:45
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save troelskn/751517 to your computer and use it in GitHub Desktop.
Save troelskn/751517 to your computer and use it in GitHub Desktop.
camelize + underscore in php
<?php
/**
* Transforms an under_scored_string to a camelCasedOne
*/
function camelize($scored) {
return lcfirst(
implode(
'',
array_map(
'ucfirst',
array_map(
'strtolower',
explode(
'_', $scored)))));
}
/**
* Transforms a camelCasedString to an under_scored_one
*/
function underscore($cameled) {
return implode(
'_',
array_map(
'strtolower',
preg_split('/([A-Z]{1}[^A-Z]*)/', $cameled, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)));
}
@deudjuimw
Copy link

Great !!! Thank you...

@thagenbeek
Copy link

Awesome, so elegent

@hgati
Copy link

hgati commented Apr 6, 2015

Super Awesome !!

@philippecarle
Copy link

Take a look at the same functions in Symfony's Container : https://github.com/symfony/symfony/blob/2.8/src/Symfony/Component/DependencyInjection/Container.php
Elegant + super-tested = 💯

@khusseini
Copy link

function camelize($string) {
    return preg_replace('/[-_]([a-z])/e', 'strtoupper("$1")', $string);
}

function underscore($string) {
    return preg_replace('/([a-z])([A-Z])/e', '"$1" . strtolower("_$2")', $string); 
}

@NemoD503
Copy link

NemoD503 commented Feb 8, 2016

@MozzyMoz flag /e is deprecated, so you code will not work on php v >= 5.5.0

@khusseini
Copy link

@NemoD503, thanks for the heads-up. I was about to replace it with a preg_replace_callback but the camelize function in the Symfony DI-Container looks nicer

@salarmehr
Copy link

salarmehr commented Aug 2, 2019

@nemo

function camelize(string $string): string
{
    return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $string))));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment