我将所有单词大写,然后将a 、 of 和之类的单词小写。第一个词和最后一个词应保持大写。我尝试使用而不是 \b,这导致了一些奇怪的问题。我也尝试过,但这似乎并不意味着“不是字符串结尾”\s
[^$]
function titleize($string){
return ucfirst(
preg_replace("/\b(A|Of|An|At|The|With|In|To|And|But|Is|For)\b/uie",
"strtolower('$1')",
ucwords($string))
);
}
这是我试图修复的唯一失败的测试。最后的“in”应保持大写。
titleize("gotta give up, gotta give in");
//Gotta Give Up, Gotta Give In
这些测试通过:
titleize('if i told you this was killing me, would you stop?');
//If I Told You This Was Killing Me, Would You Stop?
titleize("we're at the top of the world (to the simple two)");
//We're at the Top of the World (to the Simple Two)
titleize("and keep reaching for those stars");
//And Keep Reaching for Those Stars