Posted By

Sverri on 07/28/10


Tagged

String camelcase manipulation


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

osirisinternet
lolindirfaelivrin
PhunkRabbit
canberkol


Camel Case a string


 / Published in: PHP
 

Turn a string into camelcase. You can optionally set a custom regex delimiter.

  1. if ( ! function_exists('camelCase'))
  2. {
  3. function camelCase($subject, $delimiters=' _-', $lcfirst=true)
  4. {
  5. if ( ! is_string($subject))
  6. {
  7. throw new Exception("Subject must be of type string");
  8. }
  9. $subject = preg_replace('/[\s]+/', ' ', $subject);
  10.  
  11. $subject = preg_split("/[$delimiters]/", $subject, -1, PREG_SPLIT_NO_EMPTY);
  12.  
  13. foreach ($subject as $key => &$word)
  14. {
  15. $word = preg_replace('/[[:punct:]]/', '', $word);
  16.  
  17. if (preg_match('/[A-Z]+$/', $word)) $word = ucfirst($word);
  18.  
  19. else $word = ucfirst( strtolower($word) );
  20. }
  21. $subject = implode('', $subject);
  22.  
  23. if ($lcfirst)
  24. {
  25. return function_exists('lcfirst') ? lcfirst($subject)
  26. :
  27. strtolower($subject[0]).substr($subject,1);
  28. }
  29. return $subject;
  30. }
  31. }
  32.  
  33. // "usingPHPTurnThisIntoCamelCASENow"
  34. echo camelCase("Using PHP turn This into camelCASE, now!");

Report this snippet  

You need to login to post a comment.