I have some data that I'm looping through and I'm using the below line to transform all caps into mixed caps appropriately:
$str = ucwords(strtolower(trim($str)));
Which is great except that it doesn't work so great within parentheses. So I'm trying to run the below line afterwards to fix that problem, but it's not having any impact. I'm seeing zero change.
$str = preg_replace('/\((.+)\)/e', "ucwords('$0')", $str);
It should turn:
Some Product (with Caps In Paren)
Into:
Some Product (With Caps In Paren)
Use preg_replace_callback
instead, using /e
modifier is frowned upon (and it's deprecated since PHP 5.5):
$str = preg_replace_callback('/(?<=\()[^)]+(?=\))/', function($matches) {
return ucwords(strtolower(trim($matches[0])));
}, $str);
Demo. Note that I've changed the pattern as well. It now uses lookaround assertions instead of capturing groups.
If mbstring extension is available, use mb_convert_case which converts as desired.
$str = mb_convert_case($str, MB_CASE_TITLE, "ASCII");
converts to:
Some Product (With Caps In Paren)
Specify encoding if needed.
If by "doesn't work great within parentheses", you mean that it can't get words within parentheses, you can use the optional modifier:
$str = ucwords(strtolower("My string (with Caps in parens)"), '( ');
This will make it consider every space and parentheses as the start of a new word, and capitalize it.