我有一些我正在循环的数据,我正在使用以下行将所有上限适当地转换为混合上限:
$str = ucwords(strtolower(trim($str)));
除了它在括号内不起作用之外,哪个很好。所以我试图在之后运行以下行来解决这个问题,但它没有任何影响。我看到零变化。
$str = preg_replace('/\((.+)\)/e', "ucwords('$0')", $str);
应该转:
Some Product (with Caps In Paren)
分为:
Some Product (With Caps In Paren)
答案 0 :(得分:1)
如果"在括号内并不能很好地工作",你的意思是它不能在括号内得到单词,你可以使用可选的修饰符:
$str = ucwords(strtolower("My string (with Caps in parens)"), '( ');
这将使它将每个空格和括号视为新单词的开头,并将其大写。
答案 1 :(得分:0)
使用preg_replace_callback
代替,使用/e
修饰符不受欢迎(自PHP 5.5以来它已被弃用):
$str = preg_replace_callback('/(?<=\()[^)]+(?=\))/', function($matches) {
return ucwords(strtolower(trim($matches[0])));
}, $str);
Demo。请注意,我也改变了模式。它现在使用外观断言而不是捕获组。
答案 2 :(得分:0)
如果mbstring扩展程序可用,请使用mb_convert_case根据需要进行转换。
$str = mb_convert_case($str, MB_CASE_TITLE, "ASCII");
转换为:
Some Product (With Caps In Paren)
如果需要,请指定encoding。