47

ユーザー提供の文字列を標準化したい。名前の最初の文字を大文字にします。2つの姓を入力した場合は、最初の名前と2番目の名前を大文字にします。たとえば、誰かが次のように入力した場合:

marriedname maidenname

Marriedname Maidenname名前が3つ以上ある場合は、これを次のように変換します。

もう1つのシナリオは、誰かの名前にアポストロフィが含まれている場合です。誰かが入った場合:

o'connell

これはに変換する必要がありO'Connellます。

私が使用していたもの:

ucfirst(strtolower($last_name));

ただし、おわかりのように、すべてのシナリオで機能するとは限りません。

4

10 に答える 10

45

これにより、すべての単語の最初の文字と、アポストロフィの直後の文字が大文字になります。他のすべての文字は小文字になります。それはあなたのために働くはずです:

str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($last_name))));
于 2012-01-04T23:55:18.513 に答える
29

あなたは言葉のためにこれを試すことができます

<?php echo ucwords(strtolower('Dhaka, JAMALPUR, sarishabari')) ?>

結果は次のとおりです。Dhaka, Jamalpur, Sarishabari

于 2015-01-06T14:33:12.083 に答える
24

これらはいずれもUTF8に対応していないため、これが問題なく機能するものです(これまでのところ)

function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI"))
{
    /*
     * Exceptions in lower case are words you don't want converted
     * Exceptions all in upper case are any words you don't want converted to title case
     *   but should be converted to upper case, e.g.:
     *   king henry viii or king henry Viii should be King Henry VIII
     */
    $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
    foreach ($delimiters as $dlnr => $delimiter) {
        $words = explode($delimiter, $string);
        $newwords = array();
        foreach ($words as $wordnr => $word) {
            if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
                // check exceptions list for any words that should be in upper case
                $word = mb_strtoupper($word, "UTF-8");
            } elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
                // check exceptions list for any words that should be in upper case
                $word = mb_strtolower($word, "UTF-8");
            } elseif (!in_array($word, $exceptions)) {
                // convert to uppercase (non-utf8 only)
                $word = ucfirst($word);
            }
            array_push($newwords, $word);
        }
        $string = join($delimiter, $newwords);
   }//foreach
   return $string;
}

使用法:

$s = 'SÃO JOÃO DOS SANTOS';
$v = titleCase($s); // 'São João dos Santos' 
于 2013-07-23T18:06:15.173 に答える
4

この組み込み関数を使用します。

ucwords('string');
于 2013-03-14T10:33:40.640 に答える
2

私はあなたのためにすべてのシナリオをカバーする1つの良い答えがあるとは思わない。のPHP.netフォーラムにucwordsはかなりの量の議論がありますが、すべてに答えがあるものはないようです。大文字を使用するか、ユーザーの入力をそのままにして標準化することをお勧めします。

于 2012-01-05T00:54:49.183 に答える
1

preg_replaceフラグとともに使用できますe(php関数を実行します):

function processReplacement($one, $two)
{
  return $one . strtoupper($two);
}

$name = "bob o'conner";
$name = preg_replace("/(^|[^a-zA-Z])([a-z])/e","processReplacement('$1', '$2')", $name);

var_dump($name); // output "Bob O'Conner"

おそらく正規表現のパターンは改善される可能性がありますが、私が行ったことは次のとおりです。

  • $1行頭またはアルファベット以外の文字のいずれかです。
  • $2小文字の英字です

次に、これらの両方を単純な関数の結果に置き換えprocessReplacement()ます。

PHP 5.3をお持ちの場合はprocessReplacement()、無名関数を作成する価値があります。

于 2012-01-05T00:05:57.973 に答える
1

これは、メインの質問に対するもう少し単純で直接的な答えです。以下の関数は、PHPのアプローチを模倣しています。PHPが将来名前空間でこれを拡張する場合に備えて、最初にテストがチェックされます。私はワードプレスのインストールですべての言語にこの防水を使用しています。

$str = mb_ucfirst($str, 'UTF-8', true);

これにより、Qがそうであったように、最初の文字が大文字になり、他のすべての文字が小文字になります。3番目の引数がfalse(デフォルト)に設定されている場合、文字列の残りの部分は操作されません。

// Extends PHP
if (!function_exists('mb_ucfirst')) {

function mb_ucfirst($str, $encoding = "UTF-8", $lower_str_end = false) {
    $first_letter = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding);
    $str_end = "";
    if ($lower_str_end) {
        $str_end = mb_strtolower(mb_substr($str, 1, mb_strlen($str, $encoding), $encoding), $encoding);
    } else {
        $str_end = mb_substr($str, 1, mb_strlen($str, $encoding), $encoding);
    }
    $str = $first_letter . $str_end;
    return $str;
}

}
于 2013-11-27T14:09:33.390 に答える
1

これは、PHPでラテン語の名前を大文字化するための、高度に設計された、しかしかなり包括的なソリューションです。それはあなたのすべての資本化の問題を解決します。それらのすべて。

/**
 * Over-engineered solution to most capitalisation issues.
 * 
 * @author https://stackoverflow.com/users/429071/dearsina
 * @version 1.0
 */ 
class str {
    /**
     * Words or abbreviations that should always be all uppercase
     */
    const ALL_UPPERCASE = [
        "UK",
        "VAT",
    ];

    /**
     * Words or abbreviations that should always be all lowercase
     */
    const ALL_LOWERCASE = [
        "and",
        "as",
        "by",
        "in",
        "of",
        "or",
        "to",
    ];

    /**
     * Honorifics that only contain consonants.
     *
     */
    const CONSONANT_ONLY_HONORIFICS = [
        # English
        "Mr",
        "Mrs",
        "Ms",
        "Dr",
        "Br",
        "Sr",
        "Fr",
        "Pr",
        "St",

        # Afrikaans
        "Mnr",
    ];

    /**
     * Surname prefixes that should be lowercase,
     * unless not following another word (firstname).
     */
    const SURNAME_PREFIXES = [
        "de la",
        "de las",
        "van de",
        "van der",
        "vit de",
        "von",
        "van",
        "del",
        "der",
    ];

    /**
     * Capitalises every (appropriate) word in a given string.
     *
     * @param string|null $string
     *
     * @return string|null
     */
    public static function capitalise(?string $string): ?string
    {
        if(!$string){
            return $string;
        }

        # Strip away multi-spaces
        $string = preg_replace("/\s{2,}/", " ", $string);

        # Ensure there is always a space after a comma
        $string = preg_replace("/,([^\s])/", ", $1", $string);

        # A word is anything separated by spaces or a dash
        $string = preg_replace_callback("/([^\s\-\.]+)/", function($matches){
            # Make the word lowercase
            $word = mb_strtolower($matches[1]);

            # If the word needs to be all lowercase
            if(in_array($word, self::ALL_LOWERCASE)){
                return strtolower($word);
            }

            # If the word needs to be all uppercase
            if(in_array(mb_strtoupper($word), self::ALL_UPPERCASE)){
                return strtoupper($word);
            }

            # Create a version without diacritics
            $transliterator = \Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;', \Transliterator::FORWARD);
            $ascii_word = $transliterator->transliterate($word);


            # If the word contains non-alpha characters (numbers, &, etc), with exceptions (comma, '), assume it's an abbreviation
            if(preg_match("/[^a-z,']/i", $ascii_word)){
                return strtoupper($word);
            }

            # If the word doesn't contain any vowels, assume it's an abbreviation
            if(!preg_match("/[aeiouy]/i", $ascii_word)){
                # Unless the word is an honorific
                if(!in_array(ucfirst($word), self::CONSONANT_ONLY_HONORIFICS)){
                    return strtoupper($word);
                }
            }

            # If the word contains two of the same vowel and is 3 characters or fewer, assume it's an abbreviation
            if(strlen($word) <= 3 && preg_match("/([aeiouy])\1/", $word)){
                return strtoupper($word);
            }

            # Ensure O'Connor, L'Oreal, etc, are double capitalised, with exceptions (d')
            if(preg_match("/\b([a-z]')(\w+)\b/i", $word, $match)){
                # Some prefixes (like d') are not capitalised
                if(in_array($match[1], ["d'"])){
                    return $match[1] . ucfirst($match[2]);
                }

                # Otherwise, everything is capitalised
                return strtoupper($match[1]) . ucfirst($match[2]);
            }

            # Otherwise, return the word with the first letter (only) capitalised
            return ucfirst($word);
            //The most common outcome
        }, $string);

        # Cater for the Mc prefix
        $pattern = "/(Mc)([b-df-hj-np-tv-z])/";
        //Mc followed by a consonant
        $string = preg_replace_callback($pattern, function($matches){
            return "Mc" . ucfirst($matches[2]);
        }, $string);

        # Cater for Roman numerals (need to be in all caps)
        $pattern = "/\b((?<![MDCLXVI])(?=[MDCLXVI])M{0,3}(?:C[MD]|D?C{0,3})(?:X[CL]|L?X{0,3})(?:I[XV]|V?I{0,3}))\b/i";
        $string = preg_replace_callback($pattern, function($matches){
            return strtoupper($matches[1]);
        }, $string);

        # Cater for surname prefixes (must be after the Roman numerals)
        $pattern = "/\b (".implode("|", self::SURNAME_PREFIXES).") \b/i";
        //A surname prefix, bookended by words
        $string = preg_replace_callback($pattern, function($matches){
            return strtolower(" {$matches[1]} ");
        }, $string);

        # Cater for ordinal numbers
        $pattern = "/\b(\d+(?:st|nd|rd|th))\b/i";
        //A number suffixed with an ordinal
        $string = preg_replace_callback($pattern, function($matches){
            return strtolower($matches[1]);
        }, $string);

        # And we're done done
        return $string;
    }
}

遊びます

于 2021-12-16T12:09:12.557 に答える
0

最初に大文字小文字に変換し、次に最初のアポストロフィを見つけて、次の文字を大文字にします。アポストロフィの後に文字があることを確認するために、多くのチェックを追加する必要があります。このコードは、1つのアポストロフィでのみ機能します。例:「メアリーオカラハンオコネル」。

$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
$pos = strpos($str, "'");
if ($pos != FALSE)
{
     $str[$pos+1] = strtoupper($str[$pos+1]);
}
于 2012-01-05T00:12:36.287 に答える
0

WordPressを使用している場合は、次を使用します。

function archive_title() {
$title = '<h1>' . ucwords( single_tag_title( '', false ) )  . '</h1>';
}
于 2021-10-02T22:56:44.910 に答える