Skip to content

Instantly share code, notes, and snippets.

@arobinski
Last active September 6, 2022 09:32
Show Gist options
  • Save arobinski/27419c8f309d74a8d0cb to your computer and use it in GitHub Desktop.
Save arobinski/27419c8f309d74a8d0cb to your computer and use it in GitHub Desktop.
Change CamelCaseString to underscore_style_string
/**
* Changes a CamelCaseString into a string_with_underscores.
*
* @param string $string CamelCase string
* @return string string_with_underscores
*/
public static function camelCaseToUnderscoreStyle($string)
{
return preg_replace_callback(
'|[A-Z]|',
function ($match) {
return '_' . strtolower($match[0]);
},
lcfirst($string)
);
}
@linxlad
Copy link

linxlad commented Jul 8, 2015

Taking into account unicode support.
http://phpfiddle.org/main/code/sy15-vtqp

/**
 * Zmieniamy string CamelCase na pisane_z_podkresleniami.
 *
 * @param string $string String CamelCase
 * @return string string_z_podkresleniami
 */
public static function camelCaseToUnderscoreStyle($string)
{
    // Default patterm
    $pattern = array('#(?<=(?:[A-Z]))([A-Z]+)([A-Z][A-z])#', '#(?<=(?:[a-z0-9]))([A-Z])#');

    // Check fo unicode support
    $unicodeSupportEnabled = (@preg_match('/\pL/u', 'a')) ? true : false;

    if ($unicodeSupportEnabled) {
        // Change pattern for unicode support
        $pattern = array('#(?<=(?:\p{Lu}))(\p{Lu}\p{Ll})#','#(?<=(?:\p{Ll}|\p{Nd}))(\p{Lu})#');
    }

    return preg_replace_callback(
        $pattern,
        function ($match) {
            return '_' . strtolower($match[0]);
        },
        lcfirst($string)
    );
}

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