Skip to content

Instantly share code, notes, and snippets.

@reinislejnieks
Last active August 23, 2018 20:32
Show Gist options
  • Save reinislejnieks/8361b92e6a1fc174b7326f06405cf852 to your computer and use it in GitHub Desktop.
Save reinislejnieks/8361b92e6a1fc174b7326f06405cf852 to your computer and use it in GitHub Desktop.
Here are two PHP functions to convert strings between underscore format and camel case
<?php
/**
* Translates a camel case string into a string with
* underscores (e.g. firstName -> first_name)
*
* @param string $str String in camel case format
* @return string $str Translated into underscore format
*/
function fromCamelCase($str) {
$str[0] = strtolower($str[0]);
$func = create_function('$c', 'return "_" . strtolower($c[1]);');
return preg_replace_callback('/([A-Z])/', $func, $str);
}
/**
* Translates a string with underscores
* into camel case (e.g. first_name -> firstName)
*
* @param string $str String in underscore format
* @param bool $capitaliseFirstChar If true, capitalise the first char in $str
* @return string $str translated into camel caps
*/
function toCamelCase($str, $capitaliseFirstChar = false) {
if($capitaliseFirstChar) {
$str[0] = strtoupper($str[0]);
}
$func = function($c){ return strtoupper($c[1]);};
return preg_replace_callback('/_([a-z])/', $func, $str);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment