PHP: Convert String to camelCase String

PHP function that converts a string into a camelCase string.

For example:

Hello World

will be converted to

helloWorld

public static function camelCase($str, array $noStrip = [])
{
        // non-alpha and non-numeric characters become spaces
        $str = preg_replace('/[^a-z0-9' . implode("", $noStrip) . ']+/i', ' ', $str);
        $str = trim($str);
        // uppercase the first character of each word
        $str = ucwords($str);
        $str = str_replace(" ", "", $str);
        $str = lcfirst($str);

        return $str;
}

There are many reason why you might need a function to convert a string to a camel case string. A common example would be to convert a part of the URL into the name of a Controller class that would be responsible for handling that request in an MVC implementation.

One Reply to “PHP: Convert String to camelCase String”

Post a Comment