How to convert a string to title case in PHP

3 Answers

0 votes
echo ucwords(strtolower("string programming functions")) . "\n";

echo ucwords(strtolower("STRING PROGRAMMING FUNCTIONS")) . "\n";



/*
 
run:
 
String Programming Functions
String Programming Functions
 
*/


answered Aug 29, 2014 by avibootz
edited May 8, 2024 by avibootz
0 votes
function ToTitleCase($string) { 
    $len = strlen($string); 
    $i = 0; 
    $last = ""; 
    $title = "";
       
    $string = strtoupper($string); 
    while ($i < $len) {
        $char = substr($string, $i, 1); 
        if (preg_match("/[A-Z]/", $last))
            $title .= strtolower($char); 
        else
            $title .= strtoupper($char); 
        $last = $char; 
        $i++; 
    }
     
    return($title); 
} 
  
  
echo ToTitleCase("string programming functions") . "\n";
 
echo ToTitleCase("STRING PROGRAMMING FUNCTIONS") . "\n";
 
 
 
/*
  
run:
  
String Programming Functions
String Programming Functions
  
*/

 



answered May 8, 2024 by avibootz
0 votes
function ToTitleCase($string) { 
    $string = strtolower($string);
    $words = explode(" ", $string); 
    
    $titleCaseWords = array_map('ucfirst', $words); 
  
    $titleCaseString = implode(" ", $titleCaseWords); 
    
    return $titleCaseString;
} 
 
 
echo ToTitleCase("string programming functions") . "\n";

echo ToTitleCase("STRING PROGRAMMING FUNCTIONS") . "\n";



/*
 
run:
 
String Programming Functions
String Programming Functions
 
*/

 



answered May 8, 2024 by avibootz
...