top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to make the first letter of each word Upper Case using PHP?

+1 vote
901 views
How to make the first letter of each word Upper Case using PHP?
posted Jul 11, 2014 by Amanpreet Kaur

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

You will have to use ucfirst and loop through every word, checking e.g. an array of exceptions for each one.

Something like the following:

$exclude = array('and', 'not');
$words = explode(' ', $string);
foreach($words as $key => $word) {
    if(in_array($word, $exclude)) {
        continue;
    }
    $words[$key] = ucfirst($word);
}
$newString = implode(' ', $words);
answer Jul 12, 2014 by Vrije Mani Upadhyay
0 votes

This is a very useful function for titles and headings on pages, particularly if they may have been entered by the user and you want to sanitize what they entered so that your pages are nice and uniform.

It's a very simple function to use, as you can see here:

<?php $mystring = "i think this is a great page title"; echo ucwords($mystring); ?>
OUTPUT: I Think This Is A Great Page Title

answer Jul 15, 2014 by Rahul Mahajan
...