note 129291 added to function.ucwords
| From: | johngreenbury@gmail.com | Date: | Thu, 29 Feb 2024 05:16:40 +0000 |
| Subject: | note 129291 added to function.ucwords | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221216@lists.php.net to get a copy of this message | ||
This function will uppercase the first character of each word in a string except small words. Can
retain uppercase abbreviations as required. Will also correctly capitalize text inside ().
<?php
function formatText($string) {
// Note the space before and after each word.
$exceptions = array(" and "," as "," but "," for ","
if "," nor "," or "," so "," yet "," a
"," an "," the "," as "," at "," by ","
for "," in "," of "," off "," on "," per
"," to "," up "," via "," it ", " is ");
$retain = array(" LA ", " NY ");
$pos = strpos($string, "(");
if ($pos === false) {
$string = ucwords(strtolower($string));
} else {
$string = strtolower($string);
$string = str_replace('( ', '(', ucwords(str_replace('(', '(
', $string)));
}
// Non-English characters (option).
$string = mb_ucwords($string); // (function) mb_convert_case($string, MB_CASE_TITLE,
'UTF-8');
// Replace.
for ($i=0; $i<count($exceptions); $i++) {
if (strpos($string, ucwords($exceptions[$i]))) {
$string = str_replace(ucwords($exceptions[$i]), $exceptions[$i], $string);
}
}
for ($i=0; $i<count($retain); $i++) {
if (strpos($string, ucwords(strtolower($retain[$i])))) {
$string = str_replace(ucwords(strtolower($retain[$i])), $retain[$i], $string);
}
}
return $string;
}
?>
Usage:
<?php
$string = SUNDAY - THERE IS A NEW TOUR STARTING IN LA FOR (ALL) MEMBERS"
$string = formatText($string);
echo $string;
Result: Sunday - There is a New Tour Starting in LA for (All) Members
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.131 (proxied: 144.139.181.163)
----
Manual Page -- https://php.net/manual/en/function.ucwords.php
Edit -- https://main.php.net/note/edit/129291
Del: integrated -- https://main.php.net/note/delete/129291/integrated
Del: useless -- https://main.php.net/note/delete/129291/useless
Del: bad code -- https://main.php.net/note/delete/129291/bad+code
Del: spam -- https://main.php.net/note/delete/129291/spam
Del: non-english -- https://main.php.net/note/delete/129291/non-english
Del: in docs -- https://main.php.net/note/delete/129291/in+docs
Del: other reasons-- https://main.php.net/note/delete/129291
Reject -- https://main.php.net/note/reject/129291
Search -- https://main.php.net/manage/user-notes.php