Craig Francis


PHP Camel Notation

If you like to use camel notation, the following functions might be useful.

function camel2human($text) {
return ucfirst(preg_replace('/([a-z])([A-Z])/', '\1 \2', $text));
}

function human2camel($text) {

if (!isset($text[0])) {
return '';
}

$text = ucwords(strtolower($text));
$text = preg_replace('/[^a-zA-Z0-9]/', '', $text);
$text[0] = strtolower($text[0]);

return $text;

}

And for an example of their usage...

echo camel2human('exampleCamelText');
// OUTPUT: Example Camel Text

echo camel2human('articleTopic');
// OUTPUT: Article Topic

echo human2camel('Example Camel Text');
// OUTPUT: exampleCamelText

echo human2camel('Article - Topic');
// OUTPUT: articleTopic

This could be used on blogging software, where you can use the title of a post and pass it though the "human2camel" function to generate the pages URL.

Please note that these functions do not play well with capitalised abbreviations, as each capitalised letter represents the beginning of a new word.

Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.