PHP Camel Case functions

August 10th, 2009 by paul Leave a reply »

Here are two PHP functions to convert strings between underscore format and camel case.
E.g. from firstName to first_name and vice versa.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
  /**
   * Translates a camel case string into a string with underscores (e.g. firstName -&gt; first_name)
   * @param    string   $str    String in camel case format
   * @return    string            $str Translated into underscore format
   */
  function from_camel_case($str) {
    $str[0] = strtolower($str[0]);
    $func = create_function('$c', 'return "_" . strtolower($c[1]);');
    return preg_replace_callback('/([A-Z])/', $func, $str);
  }
 
  /**
   * Translates a string with underscores into camel case (e.g. first_name -&gt; firstName)
   * @param    string   $str                     String in underscore format
   * @param    bool     $capitalise_first_char   If true, capitalise the first char in $str
   * @return   string                              $str translated into camel caps
   */
  function to_camel_case($str, $capitalise_first_char = false) {
    if($capitalise_first_char) {
      $str[0] = strtoupper($str[0]);
    }
    $func = create_function('$c', 'return strtoupper($c[1]);');
    return preg_replace_callback('/_([a-z])/', $func, $str);
  }
?>
Advertisement

18 comments

  1. Joshua Reed says:

    Thought I might offer one way to do the latter w/out regexp.

    function scoresToCamel( $str, $ucfirst = false ) {
      $parts = explode('_', $str);
      $parts = $parts ? array_map('ucfirst', $parts) : array($str);
      $parts[0] = $ucfirst ? ucfirst($parts[0]) : lcfirst($parts[0]);
      return implode('', $parts);
    }
  2. paul says:

    Hi Joshua,
    Thanks for that – I think it’s worth mentioning though that lcfirst is only available on PHP >= 5.3 – so this may be useful:

    <?php
    if(!function_exists('lcfirst')) {
        function lcfirst($str) {
            return strtolower(substr($str, 0, 1)) . substr($str, 1);
        }
    }
    ?>

    Paul

  3. Tim says:

    Well done, thanks – useful cleanly written functions. I like the lambda style functions, underused in PHP.

  4. Jim says:

    < ?PHP
    //convert camelcase to normal string with spaces
    //RadioProgramWhatChristiansShouldBe becomes
    //Radio Program What Christians Should Be
    function un_camelcase_string($str)
    {
    $newstr = '';
    for($i = 0; $i 0 && ctype_upper($str{$i}))
    {
    $newstr .= ' '.$str{$i};
    }
    else
    {
    $newstr .= $str{$i};
    }
    }
    $str = $newstr;
    return $str;
    }
    ?>

  5. Dennis says:

    Other than the uh …. plug … in the string of the last example, it seems best: No doubt fastest, and probably more language/utf8 compatible.

  6. Anton Muraviev says:

    // convertSomeString in convert_some_string
    $string = preg_replace(‘~([A-Z])~’, ‘_$1′, $string);
    $string = strtolower($string);
    return trim($string, ” _”);

  7. Corey says:

    Thanks for the functions!

    Just a word of caution to anyone using the create_function function: I was using it to translate database names to class property names 10,000+ times in a single script and started noticing I was having some memory leakage. Long story short, I found out that the functions created via create_function were never getting garbage collected and they were just hanging around taking up memory. Now I am just using

    return preg_replace(“/\s+([a-z])/ie”, ’strtoupper(“$1″)’, trim($str));

    for toCamelCase and Anton’s solution for fromCamelCase

  8. Benjamin says:

    Thanks for these great functions.
    I modified them a bit to fit my needs. If someone might need a unicode version of them splitted into four functions (camelCase to undescore, PascalCase to underscore and reversed), feel free to visit my post about it:
    http://www.webdevblog.info/php/convert-strings-between-camelcasepascalcase-and-underscored-notation/

  9. Anees says:

    What about this?

    join(”, array_map(“ucwords”, explode(‘_’, $str_uscored)))

  10. Andy says:

    Anees, your solution is interesting, but prevents the use of lower camel case (which starts with lowercase).

  11. Ward Bekker says:

    Hi Paul,

    create_function unfortunately leaks memory by default, because PHP never garbage collects create_function results.

    So, call the two functions in a loop and see your memory grow and grow.

    Below my current implementation:


    public static function fromCamelCase($str)
    {
    $str[0] = strtolower($str[0]);
    return preg_replace('/([A-Z])/e', "'_' . strtolower('\\1')", $str);
    }

    public static function toCamelCase($str, $capitaliseFirstChar = false)
    {
    if ($capitaliseFirstChar) {
    $str[0] = strtoupper($str[0]);
    }

    return preg_replace('/_([a-z])/e', "strtoupper('\\1')", $str);
    }

  12. Charlie Chan says:

    Works like a charm thanks for the tips

  13. Michael says:

    function toCamelCase($word) {
    return lcfirst(str_replace(‘ ‘, ”, ucwords(strtr($word, ‘_-’, ‘ ‘))));
    }

  14. Steven Wright says:

    thanks a lot for these functions.

Leave a Reply