Created
December 22, 2010 13:45
-
-
Save troelskn/751517 to your computer and use it in GitHub Desktop.
camelize + underscore in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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))); | |
} |
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 = 💯
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);
}
@MozzyMoz flag /e is deprecated, so you code will not work on php v >= 5.5.0
@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
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
Super Awesome !!