tags:

views:

93

answers:

3

I have names like this:

$str = 'JAMES "JIMMY" SMITH'

I run strtolower, then ucwords, which returns this:

$proper_str = 'James "jimmy" Smith'

I'd like to capitalize the second letter of words in which the first letter is a double quote. Here's the regexp. It appears strtoupper is not working - the regexp simply returns the unchanged original expression.

$proper_str = preg_replace('/"([a-z])/',strtoupper('$1'),$proper_str);

Any clues? Thanks!!

+2  A: 

Probably the best way to do this is using preg_replace_callback():

$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('!\b[a-z]!', 'upper', $str);

function upper($matches) {
  return strtoupper($matches[0]);
}

You can use the e (eval) flag on preg_replace() but I generally advise against it. Particularly when dealing with external input, it's potentially extremely dangerous.

cletus
I got an error that 'upper' is not a valid callback. When I replaced 'upper' with 'strtoupper', I got 'ARRAY' instead of capital letter 'J'
Summer
@Summer then you didn't define the `upper()` function as per my code snippet.
cletus
How right you are. Thanks.
Summer
+1  A: 

Use the e modifier to have the substitution be evaluated:

preg_replace('/"[a-z]/e', 'strtoupper("$0")', $proper_str)

Where $0 contains the match of the whole pattern, so " and the lowercase letter. But that doesn’t matter since the " doesn’t change when send through strtoupper.

Gumbo
Worked like a charm. Thanks.
Summer
I think I made it more difficult than it needs to be as `strtoupper('"')==='"'`. ;-)
Gumbo
A: 

Something like this might do the trick:

preg_replace("/(\w+)/e", "ucwords(strtolower('$1'))", $proper_str);
Matt Gibson