Make first letter uppercase and the rest lowercase in a string

大憨熊 提交于 2019-11-27 11:29:09

问题


All, I'm trying to insert a last name into a database. I'd like the first letter to be capitalized for the name and if they have use two last names then capitalize the first and second names. So for example if someone enters:

marriedname maidenname

It would convert this to Marriedname Maidenname and so on if there is more then two names. The other scenario is is someone has an apostrophe in their name, so is there anyway to do it if someone enters:

o'connell

This would need to convert to O'Connell. I was using:

ucfirst(strtolower($last_name));

However, as you can tell that wouldn't work for all the scenarios. Thanks for any advice!


回答1:


This will capitalize all word's first letters, and letters immediately after an apostrophe. It will make all other letters lowercase. It should work for you:

str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($last_name))));



回答2:


you can try this for word's

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

result is: Dhaka, Jamalpur, Sarishabari




回答3:


None of these are UTF8 friendly, so here's one that works flawlessly (so far)

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;
}

Usage:

$s = 'SÃO JOÃO DOS SANTOS';
$v = titleCase($s); // 'São João dos Santos' 



回答4:


Use this built-in function:

ucwords('string');



回答5:


I don't believe there will be one good answer that covers all scenarios for you. The PHP.net forum for ucwords has a fair amount of discussions but none seem to have an answer for all. I would recommend that you standardize either using uppercase or leaving the user's input alone.




回答6:


You can use preg_replace with the e flag (execute a php function):

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"

Perhaps the regex pattern could be improved, but what I've done is:

  • $1 is either the beginning of line or any non-alphabetic character.
  • $2 is any lowercase alphabetic character

We then replace both of those with the result of the simple processReplacement() function.

If you've got PHP 5.3 it's probably worth making processReplacement() an anonymous function.




回答7:


This is a little more simple and more direct answer to the main question. the function below mimics the PHP approachs. Just in case if PHP extend this with their namespaces in the future, a test is first checked. Im using this water proof for any languages in my wordpress installs.

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

This make first letter uppercase and all other lowercase as the Q was. If the third arg is set to false (default), the rest of the string is not manipulated.

// 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;
}

}

/ Lundman




回答8:


First convert to title case, then find the first apostrophe and uppercase the NEXT character. You will need to add many checks, to ensure that there is a char after the apostrophe, and this code will only work on one apostrophe. e.g. "Mary O'Callahan O'connell".

$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
$pos = strpos($str, "'");
if ($pos != FALSE)
{
     $str[$pos+1] = strtoupper($str[$pos+1]);
}



回答9:


use like this ucfirst(strtolower($var));




回答10:


You can use strtolower and ucwords functions in PHP.

First: lower all inputted text using strtolower('inputtedtext') then capitalise all text usingucwords('strtolower')`.

Sample :

$text = 'tHis iS sOme tEXt'; <br>
$lower = strtolower($text); &ensp; //this will lower all letter from the text <br>
$upper = ucwords($lower); &ensp; //this will uppercase all first letter from the text <br>

echo $upper;

Result = This Is Some Text

You can use one line code for this with ucwords(strtolower($text));



来源:https://stackoverflow.com/questions/8735798/make-first-letter-uppercase-and-the-rest-lowercase-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!