Breaking

Sunday, March 15, 2020

How to convert first character of every word into uppercase?

 In our day-to-day project task, we may ask to get the string from a database or from the user and by using this string we need to process it as per the requirement. There may be a situation when we may get all the words in the string as uppercase e.g., user's name, address, etc.

For example:

Name : MEGAN FOX
Address: IMPRINT PR NEUEHOUSE, 6121 SUNSET BLVD., LOS ANGELES, CA 90028, USA

But in the database, we store both the strings as lowercase keeping the first character of each word as uppercase.

In this situation, we need a short but sweet solution to meet the string requirement.

We can achieve this using PHPs inbuilt functions. Let's jump right into it and then we'll discuss in depth.

<?php
$name = 'MEGAN FOX';
$address = 'IMPRINT PR NEUEHOUSE, 6121 SUNSET BLVD., LOS ANGELES';

echo ucwords(strtolower($name));
echo ucwords(strtolower($address));


//output

Megan Fox
imprint Pr Neuehouse, 6121 Sunset Blvd., Los Angeles

Basically, we've stored name and address in a separate variable. Then, we have to make sure that the provide string must be in lowercase because if the string is already in uppercase and it will make no sense to convert it directly to lowercase and in database whole string OR word always be in uppercase. 

So, we converted it into in lower case first using strtolower() function and then used ucwords() to make first character of each word as uppercase.


No comments:

Post a Comment