PHP capitalize after dash

后端 未结 9 1597
长情又很酷
长情又很酷 2021-01-17 13:46
$q = durham-region;

$q = ucfirst($q);

$q = Durham-region;

How would I capitalize the letter after the dash (Durham-Region)? Would I have to spli

相关标签:
9条回答
  • 2021-01-17 14:46

    Yes. ucfirst() simply capitalized the first letter of the string. If you want multiple letters capitalized, you must create multiple strings.

    $strings = explode("-", $string);
    $newString = "";
    foreach($strings as $string){
        $newString += ucfirst($string);
    }
    
    function ucfirst_all($delimiter, $string){
        $strings = explode("-", $string);
        $newString = "";
        foreach($strings as $string){
            $newString += ucfirst($string);
        }
        return $newString;
    }
    
    0 讨论(0)
  • 2021-01-17 14:48

    It is important to note that the solutions provided here will not work with UTF-8 strings!

    $str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει-υπέρ νωθρού κυνός";
    $str = explode('-', mb_convert_case( $str, MB_CASE_TITLE ) );
    $str = implode('-', array_map('mb_convert_case', $str, array(MB_CASE_TITLE, "UTF-8")) );
    echo $str;
    
    // str= Τάχιστη Αλώπηξ Βαφήσ Ψημένη Γη, Δρασκελίζει-Υπέρ Νωθρού Κυνόσ
    
    0 讨论(0)
  • 2021-01-17 14:49

    Updated Solution

    As of PHP 5.5, the e modifier for preg_replace has been deprecated. The best option now is to use one of the suggestions that does not use this, such as:

    $q = preg_replace_callback('/(\w+)/g', create_function('$m','return ucfirst($m[1]);'), $q)
    

    or

    $q = implode('-', array_map('ucfirst', explode('-', $q)));
    

    Original Answer

    You could use preg_replace using the e modifier this way:

    $test = "durham-region";
    $test = preg_replace("/(\w+)/e","ucfirst('\\1')", $test);
    echo $test;
    // Durham-Region
    
    0 讨论(0)
提交回复
热议问题