Using PHP to Capitalise Text

Last Updated on: April 30, 2024

There are a few useful functions built into PHP that will help you format and tidy up your text.

First, let’s take a look at switching from uppercase to lowercase, and vice versa:

// This will output: MONKEYS AND BANANAS
echo strtoupper('monkeys and bananas');

// This will output: monkeys and bananas
echo strtolower('MONKEYS and BANANAS');

Next, we will take a look at how to capitalise the first letter of one or multiple words. There are two functions you can use, depending on if you want to capitalise the first word only or all the words:

// This will output: Frogs eat dogs.
echo ucfirst('frogs eat dogs.');

// This will output: Frogs Eat Dogs.
echo ucwords('frogs eat dogs.')

One thing to watch out for is if your text is uppercase (or mostly uppercase) and you want to use ucfirst() or ucwords() to capitalise the first letters – you won’t get the desired effect. Ensure you use strtolower() first, as follows:

// This will output: FROGS EAT DOGS ON LOGS.
echo ucfirst ('FROGS EAT DOGS ON LOGS.');

// This will output: Frogs eat dogs on logs.
echo ucfirst (strtolower('FROGS EAT DOGS ON LOGS.'));

These functions are useful for tidying up any text on your website or project. If you allow users to enter text, then this is a great way to keep that clean and presentable automatically.


Get notified of new posts:


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *