phpregexpreg-replacepascalcasingsnakecasing

Convert snake_case string to PascalCase (aka StudlyCase)


Here is a sample string: hello_world_again

So it would be converted to: HelloWorldAgain

So it should be able to remove the underscore and capitalize the next letter. The first letter should also be capitalized.

I found this:

preg_replace('/(?<! )(?<!^)[A-Z]/', '_$0', $val)

But I want to reverse the process.


Solution

  • Regular expressions alone will not work here. However, you can use preg_replace_callback instead:

    $val = 'hello_world_again';
    function match_toupper($m) {
        return strtoupper($m[1]);
    }
    $val = preg_replace_callback('/(?:^|_)([a-z])/', 'match_toupper', $val);
    echo $val; // HelloWorldAgain
    

    In PHP 5.3 or later, can also use an anonymous function:

    $val = 'hello_world_again';
    $val = preg_replace_callback('/(?:^|_)([a-z])/', 
        function ($m) {
            return strtoupper($m[1]);
        }, $val);
    echo $val; // HelloWorldAgain
    

    Also, if you ignore all the warnings and cautions about the e modifier, this will work too:

    $val = 'hello_world_again';
    $val = preg_replace('/(?:^|_)([a-z])/e', 'strtoupper($1)', $val);
    echo $val; // HelloWorldAgain
    

    And here's another solution that avoids regular expressions entirely:

    $val = 'hello_world_again';
    $val = implode('', array_map(ucfirst, explode('_', $val)));
    echo $val; // HelloWorldAgain