strtocamelcase() - CamelCase in PHP

A simple function can convert normal text to so-called camel caps, or more formally known as medial capitals, more specifically to lowerCamelCase.

This can be especially useful, when a text or a string must not contain any whitespaces but should still be reasonably readable, e.g. a file name or a URL.

<?php
function strtocamelcase($str) {
    return preg_replace_callback('#[\s]+(.)#', create_function('$r', 'return strtoupper($r[1]);'), $str);
}

# Example:
$str = 'my cat and I.jpg';
echo strtocamelcase($str);
# Output: myCatAndI.jpg
?>

If the first letter of the original text is lowercase, it will stay lowercase.

In case you want to have it uppercase, just apply the function ucfirst() afterwards, or use the following function instead:

<?php
function strtocamelcase($str) {
    $str = ucwords($str);
    $str = preg_replace('#[\s]+#', '', $str);
    return $str;
}

# Example:
$str = 'my cat and I.jpg';
echo strtocamelcase($str);
# Output: MyCatAndI.jpg
?>

This does the same thing as above, except for the first letter being uppercase (UpperCamelCase).

Links