note 95325 deleted from function.ucwords by cmb
| From: | cmb@php.net | Date: | Sun, 17 Feb 2019 11:15:59 +0000 |
| Subject: | note 95325 deleted from function.ucwords by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210250@lists.php.net to get a copy of this message | ||
Note Submitter: Kovik
----
ucwords() only uses whitespace as a delimiter. I found that I needed the ability to use other
delimiters for denoting words.
Example: Transforming "content-type" into "Content-Type".
<?php
/**
* Capitalize all words
* @param string Data to capitalize
* @param string Word delimiters
* @return string Capitalized words
*/
function capitalizeWords($words, $charList = null) {
// Use ucwords if no delimiters are given
if (!isset($charList)) {
return ucwords($words);
}
// Go through all characters
$capitalizeNext = true;
for ($i = 0, $max = strlen($words); $i < $max; $i++) {
if (strpos($charList, $words[$i]) !== false) {
$capitalizeNext = true;
} else if ($capitalizeNext) {
$capitalizeNext = false;
$words[$i] = strtoupper($words[$i]);
}
}
return $words;
}
?>
Testing:
<?php
echo capitalizeWords('this is a test'); // This Is A Test
echo capitalizeWords('this-is-a-test'); // This-is-a-test
echo capitalizeWords('this is a test', ' '); // This Is A Test
echo capitalizeWords('this-is-a-test', '-'); // This-Is-A-Test
echo capitalizeWords('this-is a-test', ' '); // This-is A-test
echo capitalizeWords('this-is a-test', '-'); // This-Is a-Test
echo capitalizeWords('this-is a-test', ' -'); // This-Is A-Test
?>