PHP, regex, and capitalization

php, preg-replace, regex

Solution

You can use preg_replace_callback like this:

  $string = preg_replace_callback(
           '#(?<=-)(.)#',
           create_function(
               '$matches',
               'return strtoupper($matches[1]);'
           ),
           $string
       );

Or, with an anonymous function (using PHP ver >= 5.3.0):

$string = preg_replace_callback( '#(?<=-)(.)#', function( $matches) {
    return strtoupper( $matches[1]);
}, $string);

Live Demo: http://ideone.com/IpoCvB

Problem

I need to capitalize what my regex captures/matches. Say I wanted to capitalize the first character after a hyphen, my regex would be something like this: `-(.)` And my replacement string would be something like this: `-\U1` In `preg_replace`, I would have something like this: `$string = preg_replace('/-(.)/', '-\1', $string);` But this doesn't work in `preg_replace` (and I don't think it supports changing the case in a backreference). Suggestions?

Original source