Sam
Sam

Reputation:

Capitalise every word of a string in PHP?

As I know, strtolower makes the string all lowercase and ucfirst makes the string's first letter capitalised.

I am asking, is it possible to make every word within the string capitalised?

Example $string = "hello world" - How can I make this appear "Hello World"?

Upvotes: 2

Views: 997

Answers (2)

Paolo Bergantino
Paolo Bergantino

Reputation: 488344

You are looking for the ucwords function. Example straight from the PHP docs:

$foo = 'hello world!';
$foo = ucwords($foo);             // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar);             // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!

Upvotes: 14

jerebear
jerebear

Reputation: 6655

It's a good practice to make the entire string lowercase first just to ensure consistency.

$foo = ucwords(strtolower($string));

Upvotes: 6

Related Questions