Skip to content

Instantly share code, notes, and snippets.

@razzul
Last active September 21, 2017 09:33
Show Gist options
  • Save razzul/f4585dd2fd70e53d25548be383010daa to your computer and use it in GitHub Desktop.
Save razzul/f4585dd2fd70e53d25548be383010daa to your computer and use it in GitHub Desktop.
Switch string camel case <=> snake case

camel case <=> snake case

    /**
     * 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
     *
     * @author Rajul.Mondal
     * @since Sept 19, 2017
     */
    public static function camelToSnakeCase($str)
    {
        $str[0] = strtolower($str[0]);
        return preg_replace_callback('/([A-Z])/', function($m) { return '_' . strtolower($m[1]); }, $str);
    }

    /**
     * Translates a string with underscores into camel case (e.g. first_name > firstName)
     *
     * @param string $str String in underscore format
     * @param bool $capitalise_first_char If true, capitalise the first char in $str
     * @return string $str translated into camel caps
     *
     * @author Rajul.Mondal
     * @since Sept 19, 2017
     */
    public static function snakeToCamelCase($str, $capitaliseFirstChar = false)
    {
        if ($capitaliseFirstChar) {
            $str[0] = strtoupper($str[0]);
        }
        return preg_replace_callback('/_([a-z])/', function($m) { return strtoupper($m[1]); }, $str);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment