stormist
stormist

Reputation: 5905

In PHP, make every letter left of colon lowercase w/o use of explode,implode

Can this be done with regular expressions?

Examples

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

y-exaMPLE:testoneTWOthree becomes y-example:testoneTWOthree

Upvotes: 0

Views: 412

Answers (4)

cletus
cletus

Reputation: 625097

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.

Upvotes: 4

Galen
Galen

Reputation: 30170

$str = 'y-exaMPLE:testoneTWOthree';
function lower( $str ) {
    return strtolower( $str[1] );
}

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

Upvotes: 2

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94173

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.

Upvotes: 3

erenon
erenon

Reputation: 19118

You might take a look at preg_replace_callback

Upvotes: 3

Related Questions