As for US: You’d need a database storing the words that shall be uppercase. PHP itself is stupid, it does not know if you mean United States or us (accusative of we). Thus, the interpreter cannot decide if US in US-Pakistan is meant to be the abbreviation or the pronoun.
With such a database, you would call your upper function normally. Afterwards you would have to check if the entry is within your database and replace the occurrence in the text with the one from the database.
$string = strtolower(ucwords($string));
$words = preg_split('/\s+/', $string);
foreach ($words as $word) {
// search case-independantly
if (null !== ($correctForm = searchDatabase($word))) {
str_replace($word, $correctFrom, $string);
}
}
This is probably not optimal, but I hope it is visible what’s the way to go if PHP cannot know if a word is an abbreviation or not.
In the database you might have such entries:
us-pakistan US-Pakistan
us-politician US-politician
Or if you wanna implement it somewhat advanced even:
us-* US-*
In such a case you might also just implement it with a lot of preg_replaces(), but don’t ask me about time consumption. I guess both of these ideas are pretty slow.
As for Pakistan: Keeping letters after dashes capital is easier. You could replace -
with -
surrounded by spaces ([space]-[space]) before calling the function, then PHP would think that both of them are single words. Afterwards you could replace the [space]-[space] construction with a simple dash again.
str_replace(' - ', '-', strtolower(ucwords(str_replace('-', ' - ', $string))));
Check out the PHP-comments Ayman Safadi has posted, I guess they have much better solutions for this problem (mine was just: “What’s the first maximum-short solution coming to my mind?”).