私は、今日私が取り組んでいるアプリで実装するためにこれを書いた。私は、このコードはコメントでかなり自明だと思う。すべてのケースで100%正確ではありませんが、ほとんどの西洋人の名前を簡単に処理します。
例:
mary-jane => Mary-Jane
o'brien => O'Brien
Joël VON WINTEREGG => Joël von Winteregg
jose de la acosta => Jose de la Acosta
あなたが合うように上部の配列に任意の文字列値を追加することがあり、その中にコードが拡張可能ですあなたの要望。それを勉強し、必要な特別な機能を追加してください。
function name_title_case($str)
{
// name parts that should be lowercase in most cases
$ok_to_be_lower = array('av','af','da','dal','de','del','der','di','la','le','van','der','den','vel','von');
// name parts that should be lower even if at the beginning of a name
$always_lower = array('van', 'der');
// Create an array from the parts of the string passed in
$parts = explode(" ", mb_strtolower($str));
foreach ($parts as $part)
{
(in_array($part, $ok_to_be_lower)) ? $rules[$part] = 'nocaps' : $rules[$part] = 'caps';
}
// Determine the first part in the string
reset($rules);
$first_part = key($rules);
// Loop through and cap-or-dont-cap
foreach ($rules as $part => $rule)
{
if ($rule == 'caps')
{
// ucfirst() words and also takes into account apostrophes and hyphens like this:
// O'brien -> O'Brien || mary-kaye -> Mary-Kaye
$part = str_replace('- ','-',ucwords(str_replace('-','- ', $part)));
$c13n[] = str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', $part)));
}
else if ($part == $first_part && !in_array($part, $always_lower))
{
// If the first part of the string is ok_to_be_lower, cap it anyway
$c13n[] = ucfirst($part);
}
else
{
$c13n[] = $part;
}
}
$titleized = implode(' ', $c13n);
return trim($titleized);
}
だから、あなたが助けを必要としません。コードと...名前のリストだけ? – vcsjones
マクドナルドやマクドナルドのようなものは、姓の正しいスペルであり、それがどういう場合にその人に依存するので、これはかなり困難です。 –
なぜユーザーは自分の名前を入力しないのですか? –