views:

108

answers:

4

Can this be done with regular expressions?

Examples

x-example-HEADER:teSt becomes x-example-header:teSt

y-exaMPLE:testoneTWOthree becomes y-example:testoneTWOthree

+2  A: 

You might take a look at preg_replace_callback

erenon
+3  A: 

Use preg_replace_callback():

$output = preg_replace_callback('![a-zA-Z]+:!', 'to_lower', $input);

function to_lower($matches) {
  return strtolower($matches[0]);
}

You can't otherwise do case conversion with regular expressions except in specific cases (eg replace 'A' with 'a' is possible).

Edit: Ok, you learn something new everyday. You can do this:

$output = preg_replace('![a-zA-Z]+:!e', "strtoupper('\\1')", $input);

From Pattern Modifiers:

*e (PREG_REPLACE_EVAL)*

If this modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes () and NULL chars will be escaped by backslashes in substituted backreferences.

Only preg_replace() uses this modifier; it is ignored by other PCRE functions.

I would however shy away from eval()ing strings, especially when combined with user input it can be a very dangerous practice. I would prefer the preg_replace_callback() approach as a general rule.

cletus
+3  A: 

You can use the e modifier on a regular expression pattern when given to preg_replace (take a look at example #4 on that page) in order to call PHP code as part of the replacement:

$string = "x-example-HEADER:teSt";
$new_string = preg_replace('/(^.+)(?=:)/e', "strtolower('\\1')", $string);
// => x-example-header:teSt

The pattern will grab everything before the first colon into the first backreference, and then replace it with the strtolower function.

Daniel Vandersluis
this is news to me! thanks
Galen
+2  A: 
$str = 'y-exaMPLE:testoneTWOthree';
function lower( $str ) {
    return strtolower( $str[1] );
}

echo preg_replace_callback( '~^([^:]+)~', 'lower', $str );
Galen