Wednesday, September 16, 2015

[PHP] Spread camel case

My work has me doing Wordpress plugins from time to time. The following snippets comes from one of those projects. It's text a camel-case string and inserts spaces in front of capitals and numbers, turning the item into some more human-readable.
function spreadCamel($txt) 
 {
  $temp = substr($txt,0,1);
  for ($i = 1; $i < strlen($txt); $i++) {
   $c = substr($txt, $i, 1);
   if (ctype_upper($c) || ctype_digit($c)) {
    $temp = $temp . " ";
   }
   $temp = $temp . $c;
  }
  return $temp;
 } 
An example invocation:
echo spreadCamel("MyDogHasFleasAbout1Million");
the result of that being
My Dog Has Fleas About 1 Million
I hope that helps someone. There may be a better/faster/more efficient way of doing it. If there is, please post in the comments.

© Copyright Bruce M. Axtens, 2015

1 comment:

Bere Farno said...

Anything would always involve walking from one end of the string to the other and looking at the codepoint. The only saving I suspect would be convincing PHP to do that natively (like a regexp search and replace).

Thank you for sharing