How to uppercase first letter after a hyphen, ie Adam Smith-Jones

前端 未结 9 1457
野趣味
野趣味 2021-02-01 22:30

I\'m looking for a way to uppercase the first letter/s of a string, including where the names are joined by a hyphen, such as adam smith-jones needs to be Adam Smith-Jones.

相关标签:
9条回答
  • 2021-02-01 23:07

    Other way:

    <?php
    
    $str = 'adam smith-jones';
    
    echo preg_replace("/(-)([a-z])/e","'\\1'.strtoupper('\\2')", ucwords($str));
    
    ?>
    
    0 讨论(0)
  • 2021-02-01 23:20
    $string = implode('-', array_map('ucfirst', explode('-', $string)));
    
    0 讨论(0)
  • 2021-02-01 23:21

    Is this ok ?

        function to_upper($name)
        {
            $name=ucwords($name);
            $arr=explode('-', $name);
            $name=array();
            foreach($arr as $v)
            {
                $name[]=ucfirst($v);
            }
            $name=implode('-', $name);
            return $name;
        }
        echo to_upper("adam smith-jones");
    
    0 讨论(0)
  • 2021-02-01 23:21
    <?php
         // note - this does NOT do what you want - but I think does what you said
         // perhaps you can modify it to do what you want - or we can help if you can
         // provide a bit more about the data you need to update
        $string_of_text = "We would like to welcome Adam Smith-jones to our 3rd, 'I am addicted to stackoverflow-posting' event.";
         // both Smith-Jones and Stackoverflow-Posting should result
         // may be wrong
        $words = explode(' ',$string_of_text);
    
        foreach($words as $index=>$word) {
           if(false !== strpos('-',$word)) {
              $parts = explode('-',$word);
              $newWords = array;
              foreach($parts as $wordIndex=>$part) {
                $newWords[] = ucwords($part);
              }
              $words[$index] = implode('-',$newWords);
           }
        }
    
        $words = implode(' ',$words);
    
    ?>
    

    Something akin to this - untested - for the purposes of making sure I understand the question.

    0 讨论(0)
  • 2021-02-01 23:24
    function capWords($string) {
        $string = str_replace("-", " - ", $string);
        $string = ucwords(strtolower($string));
        $string = str_replace(" - ", "-", $string);
    
        return $string;
    }
    
    0 讨论(0)
  • 2021-02-01 23:25

    What do you think about the following code ?

    mb_convert_case(mb_strtolower($value), MB_CASE_TITLE, "UTF-8");
    

    Please note that this also handles accented characters (usefull for some languages such as french).

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