I am coding a tag system for a custom CMS built with Codeigniter and I'm trying to enforce a particular format.
Basically, I need the first letter of each word to be capitalized with the exception of the following, which should be lowercase:
- Articles: a, an, the
- Coordinating Conjunctions: and, but, or, for, nor, etc.
- Prepositions (fewer than five letters): with, on, at, to, from, by, etc.
Furthermore, if the tag starts with one of the above, it should be capitalized.
Some examples of properly formatted tags:
- Game of Thrones
- Of Mice and Men
- From First to Last
- Lord of the Rings
- Need for Speed
So far I just have:
$tag = 'Lord of the Rings';
$tag = ucwords($tag);
$patterns = array('/A/', '/An/', '/The/', '/And/', '/Of/', '/But/', '/Or/', '/For/', '/Nor/', '/With/', '/On/', '/At/', '/To/', '/From/', '/By/' );
$lowercase = array('a', 'an', 'the', 'and', 'of', 'but', 'or', 'for', 'nor', 'with', 'on', 'at', 'to', 'from', 'by' );
$formatted_tag = preg_replace($patterns, $lowercase, $tag);
// capitalize first letter of string
$formatted_tag = ucfirst($formatted_tag);
echo $formatted_tag;
This produces the correct result of Lord of the Rings, but how can I avoid duplicating the arrays? It's tedious matching them up when I add new words.
I'm sure there are some words that should be included that I'm missing, are there any existing functions or classes that I can use?