Pages

Text transformation

When dealing with user input, you will often come across people who keep their Caps Lock key permanently enabled, which can make reading what they write difficult on the eye. It also looks like they are shouting. To diminish or entirely remove this problem, use this function , which also supports three other upper- and lowercase text transformations
/*
$text A string variable containing the text to be transformed
$type A string containing the type of transformation to make:
 “u” – Capitalize all letters
 “l” – Set all letters to lowercase
 “w” – Capitalize the first letter of every word
 “s” – Capitalize the first letter of every sentence
*/

function TextTransform($text, $type) {
 switch($type)  {
 case "u": return strtoupper($text);
 case "l": return strtolower($text);
 case "w":
  $newtext = "";
  $words  = explode(" ", $text);
  foreach($words as $word)
   $newtext .= ucfirst(strtolower($word)) . " ";
  return rtrim($newtext);
 case "s":
  $newtext = "";
  $sentences = explode(".", $text);
  foreach($sentences as $sentence)
   $newtext .= ucfirst(ltrim(strtolower($sentence))) . ". ";
  return rtrim($newtext);
 }
return $text;
}
Use : The $text argument should contain the string to transform, while the second argument should be one of the four letters shown (in lowercase).
echo TextTransform("Text to transform","l")