Is it possible to make the first letter of every word uppercase
unless it is one of a group of words?
I have to get some data from a database and present it on a page as a menu. The format would be that all words would start with a capital unless they were
'and', 'of', 'the', 'a' etc.
Something like...
Vegetable and Goat's Cheese Terrine with Pineapple Pickle
rather than
Vegetable And Goat's Cheese Terrine With Pineapple Pickle

Is this possible with php?

Recommended Answers

All 7 Replies

If you want to convert any sentence to this format, you can use explode(' ', $sentence) to create an array of words from your sentence, and then process each word accordingly. (Then use implode to make a sentence again.)

That's what I thought, but was hoping there was an easier way - serves me right for being lazy :)

Not easier, but another way is to use preg_replace_callback().

Why don't you store the data in the format you need ? Change the casing before you insert it into the database.

The problem with storing the data in the format I need is that I will be building a CMS and there will be different users entering data into the database. The chance of them using the same format is not great.
I'll check out preg_replace_callback()

Well... if _you_ are building the CMS then you control the input. You can run your code before the database insert.

Yes that makes sense. Sometimes I can't see the wood for the trees.
Thanks for your help

If your list of words-to-not-capitalize is relatively short, you could do this:

$string = "vegetable and goat's cheese terrine with pineapple pickle";
$uppercase = ucwords($string);
$fixed = str_replace(array(' And ',' Of ',' The ',' A '),array(' and ',' of ',' the ',' a '),$uppercase);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.