Make first letter uppercase and the rest lowercase in a string

后端 未结 10 1716
醉梦人生
醉梦人生 2020-12-13 12:25

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 fir

相关标签:
10条回答
  • 2020-12-13 13:13

    you can try this for word's

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

    result is: Dhaka, Jamalpur, Sarishabari

    0 讨论(0)
  • 2020-12-13 13:14

    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]);
    }
    
    0 讨论(0)
  • 2020-12-13 13:20

    Use this built-in function:

    ucwords('string');
    
    0 讨论(0)
  • 2020-12-13 13:20

    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.

    0 讨论(0)
提交回复
热议问题