Skip to content

Instantly share code, notes, and snippets.

@imvaskii
Last active January 2, 2019 00:26
Show Gist options
  • Save imvaskii/3ef9be0fcb04a13dcdab68078608de89 to your computer and use it in GitHub Desktop.
Save imvaskii/3ef9be0fcb04a13dcdab68078608de89 to your computer and use it in GitHub Desktop.
Convert string to camelCase.
<?php
/**
* Convert string to camelCased format.
*
* supports strings with "-" dash case
*
* @param string $str
* @param boolean $capitalise_first_char
*
* @return string $str camelCased string.
*/
function to_camel_case( $str, $capitalise_first_char = false ) {
// Removes '-' or '_' from start/end of the string.
$str = trim( $str, '-_' );
if ( $capitalise_first_char ) {
$str[0] = strtoupper( $str[0] );
}
// Match first letter of the string after "-" or "_" and change it to uppercase,
return preg_replace_callback(
'/[_-]([a-z])/', function( $match ) {
return strtoupper( $match[1] );
}, $str
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment