Converting lowercase_with_underscores to camelCase

I have a case where I’m retrieving an array of associative arrays from a database as shown below:

Array
(
    [0] => Array
        (
            [id] => 1
            [some_id] => 100001
            [some_company_name] => Foo
            [name] => Bar
            [created] => 2008-12-25 21:13:58
            [last_updated] => 2008-12-30 23:32:43
        )

)

…but I need to represent this structure in XML. I have a pre-defined standard in my XML request/response that the element names are to be camel cased.

Aliasing the field names at the query level is just…a hack. So, I needed a way to convert “foo_bar_baz” to “fooBarBaz” before adding the XML element.

To do this, you can use preg_replace_callback() as shown below, which uses a callback function on every match found.

class FooController
{
    public function barAction()
    {
        $dao = new Some_Dao();
        $rows = $dao->getWhateverRows();

        foreach ($rows as $row) {
            foreach ($row as $key => $value) {
                // $key is "foo_bar_baz"
                $key = preg_replace_callback(
                    '/_(\w)/',
                    array($this, '_convertToCamelCase'),
                    $key);

            // $key is now "fooBarBaz"
            }
        }
    }

    private function _convertToCamelCase(array $matches)
    {
         return ucfirst($matches[1]);
    }
}

There is an e modifier that can be used with preg_replace(), but that requires the replacement string to be a valid string of PHP code. This forces the interpreter to parse the replacement string into PHP on each iteration, which can be quite inefficient. Instead, the preg_replace_callback() uses a callback function, which only needs to be parsed once.

I suppose you could easily do the reverse, though I haven’t had a need to write that code yet. :) But…there you go! A little end-of-year tip from myself and the preg_replace() examples.

  1. Hey Brian, you aught to have a look at the “Word” filters built into Zend Framework:

    http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Filter/Word/

    There is a whole bunch of them, backwards and forwards ;)

    -ralph

  2. @Ralph: wow, nice! Thanks for the heads up! Those do look pretty handy. I’d never seen them in ZF before.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>