$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
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;
}
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= Τάχιστη Αλώπηξ Βαφήσ Ψημένη Γη, Δρασκελίζει-Υπέρ Νωθρού Κυνόσ
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