функция ucwords с исключениями

Мне нужна помощь, у меня есть этот код, который содержит первый символ каждого слова в строке с исключениями. Мне нужна функция, чтобы игнорировать исключение, если оно находится в начале строки:

function ucwordss($str, $exceptions) { $out = ""; foreach (explode(" ", $str) as $word) { $out .= (!in_array($word, $exceptions)) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " "; } return rtrim($out); } $string = "my cat is going to the vet"; $ignore = array("is", "to", "the"); echo ucwordss($string, $ignore); // Prints: My Cat is Going to the Vet 

это то, что я делаю:

 $string = "my cat is going to the vet"; $ignore = array("my", "is", "to", "the"); echo ucwordss($string, $ignore); // Prints: my Cat is Going to the Vet // NEED TO PRINT: My Cat is Going to the Vet 

Solutions Collecting From Web of "функция ucwords с исключениями"

 - return rtrim($out); + return ucfirst(rtrim($out)); 

Что-то вроде этого:

 function ucwordss($str, $exceptions) { $out = ""; foreach (explode(" ", $str) as $key => $word) { $out .= (!in_array($word, $exceptions) || $key == 0) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " "; } return rtrim($out); } 

Или еще проще, перед return в вашу функцию сделайте strtoupper first letter

Сделайте это по-настоящему дешево, просто всегда сглаживая свое первое слово:

 function ucword($word){ return strtoupper($word{0}) . substr($word, 1) . " "; } function ucwordss($str, $exceptions) { $out = ""; $words = explode(" ", $str); $words[0] = ucword($words[0]); foreach ($words as $word) { $out .= (!in_array($word, $exceptions)) ? ucword($word) : $word . " "; } return rtrim($out); } 

как насчет того, чтобы вы сделали первую букву в строчном верхнем регистре, так что независимо от вашего микса вы все равно пройдете

 $string = "my cat is going to the vet"; $string = ucfirst($string); $ignore = array("is", "to", "the"); echo ucwordss($string, $ignore); 

таким образом, первое письмо строки всегда будет иметь верхний регистр