Reputation: 74
I am using ucword function to uppar case only first word as this ucwords(strtolower($var))
but sometimes I want the word to be uppar case. Please see the below example to understand clearly.
$var = "class iii";
echo ucwords(strtolower($var));
gives as **Class Iii or Class Ii or Class Iv**
What I want it should display as Class III or Class II or Class IV
to look beautiful
Upvotes: 1
Views: 755
Reputation: 1160
ucwords
will convert only first character of string in uppercase.
You have to find for all iii or iv first convert it to uppercase and then apply ucowrds to whole string.
Upvotes: 0
Reputation: 20075
Try using this instead:
<?php
function xucwords($string)
{
$words = split(" ", $string);
$newString = array();
foreach ($words as $word)
{
if(!preg_match("/^m{0,4}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})$/", $word)) {
$word = ucfirst($word);
} else {
$word = strtoupper($word);
}
array_push($newString, $word);
}
return join(" ", $newString);
}
echo xucwords('class iii');
?>
based on the function found here.
Upvotes: 1
Reputation: 5309
Try this
<?php
$var = "class iii";
$var = ucfirst(strtolower($var));
echo str_replace(substr($var, 6), strtoupper(substr($var, 6)), $var);
?>
Output:
Class III
Upvotes: -1
Reputation: 76636
You can achieve this using preg_replace_callback()
with a regex that uses positive lookahead:
/\b(?=[LXIVCDM]+\b)([a-z]+)\b/i
Explanation:
\b
- assert position at a word boundary(?=
- positive lookahead
[LXIVCDM]+
- match any character from the list one or more times\b
- assert position at a word boundary)
- end of positive lookahead[a-z]
- any alphabet\b
- assert position at a word boundaryi
- pattern modifier that makes the matching case-insensitiveCode:
$str = "class iii";
$string = preg_replace_callback('/\b(?=[LXIVCDM]+\b)([a-z]+)\b/i',
function($matches) {
return strtoupper($matches[0]);
}, ucwords(strtolower($str)));
echo $string;
Output:
Class III
Upvotes: 4
Reputation: 3068
You the below code and see my inline comments
$var = "class iii";
echo upperCaseCustomFunction($var);
upperCaseCustomFunction($string) {
$arr = explode(" ",$string);
$stringPartOne = ucwords(strtolower($arr[0])); // will return Class
$stringPartTwo = strtoupper(strtolower($arr[1])); // Will return III
return $tringPartOne." ".$stringPartTwo; // will return Class III
}
Upvotes: 0
Reputation: 1322
Simple use like below :
$var = strtolower("class ") . strtoupper("iii");
echo ucwords($var);
//Gives Class III
Upvotes: -1