Reputation: 1401
Ive been looking around for a way in PHP to have a string converted, so that the first letter becomes uppercase and the rest lower case.
At the moment I am doing what I believe is the standard way:
ucfirst(strtolower($string));
But I have found that some programming languages (ie. tcl) can do it with one cammand:
totitle
Is there a way to do this in PHP? It's not a problem as such, I'm just a curios dude :D
Thanks
Upvotes: 1
Views: 11627
Reputation: 47900
There is a single, native function that performs title-casing and is multibyte-safe. This is a very tidy solution because you don't need to prepare the string to be all lowercase before making the leading letter of all words uppercase.
Code: (Demo)
$string = "OH HeLlo world, it'S \"NiCE\" 'to' sEe you!";
echo mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');
Output:
Oh Hello World, It's "Nice" 'To' See You!
The above demonstrates that the coment at https://www.php.net/manual/en/function.mb-convert-case.php#119629 is incorrect about the behavior relating to double-quote wrapped words.
Also, in Laravel, there is a helper method that can be mentioned: title()
.
use Illuminate\Support\Str;
$converted = Str::of('a nice title uses the correct case')->title();
// A Nice Title Uses The Correct Case
Source: https://laravel.com/docs/8.x/helpers#method-fluent-str-title
Upvotes: 0
Reputation: 95
If you have multiple words in your string, ucwords()
can convert the first letter of each word to uppercase.
$string = 'hello world HELLO, wORlD HOW are You';
echo upperLowerCase($string);
function upperLowerCase($string) {
return ucwords(strtolower($string));
}
Upvotes: -1
Reputation: 9
You should go like this
<?php
$string= 'HELLO WORLD';
$string = strtolower($string);
$string = ucfirst($string);
?>
Upvotes: 0
Reputation: 5238
You can create such function yourself.
Do not forget that you should use mb_*
functions for data that was input by user. English is not the only language people use. Look at this question: ucfirst() function for multibyte character encodings
Upvotes: 0
Reputation: 5722
"Title" casing capitalizes each word in a string (i.e. every letter following white space). Your approach would result in "Gone with the wind," whereas title casing would yield "Gone With The Wind".
I wouldn't worry about it: what you're doing is simple and intuitive, and if it gets you what you want, there's not any intrinsic functions that do the same thing.
Upvotes: 0
Reputation: 3974
function totitle($string){
return ucfirst(strtolower($string));
}
And voila :)
Upvotes: 5