PHP function to convert only words in UPPERCASE to Startcase

I needed a function in PHP that would convert words in uppercase to Startcase, i.e. the first letter of the word in uppercase and the rest in lowercase. A combination of ucwords with strtolower can do that, however, I only wanted the words that were fully in uppercase to be converted, not the other words.

To give a example, I wanted
SHINKANSEN SAKURA 555 naar Hiroshima (treinpas valideren in Shinagawa station)
to be converted to
Shinkansen Sakura 555 naar Hiroshima (treinpas valideren in Shinagawa station)
(and not to)
Shinkansen Sakura 555 Naar Hiroshima (treinpas Valideren In Shinagawa Station)

You can do that relatively easily with preg_replace_callback:

This replaces any word of least 2 capital letters to a word with only the first letter capitalized.

Share

Leave a Reply

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

Spam Protection by WP-SpamFree