Jump to content

Change Form Value To Always Print Capitalized Names?


LukeGee

Recommended Posts

Hi I am new and would like to have this idea criticized. I wrote a working script in attempt to ensure that an entered value is printed as capitalized but i feel it is cumbersome and should be much more simple. If anyone would like to comment on this I would greatly appreciate it.

 

$strg = trim($_POST['user_char_name']);
$finder = '/^[a-z]/';
if (preg_match($finder, $strg , $matches)){
$up_cvar = strtoupper($matches[0]); 
$user_cname = preg_replace($finder , $up_cvar , $strg);
} else {
$user_cname = trim($_POST['user_char_name']);
}

You usually don't want to manipulate user submitted data in that way, for the simple reason that you have no way of knowing if that's what the user wants it to look like. If you insist on doing it, perhaps you overlooked ucfirst?

If you allow first & last names or possibly more, something like this could work.

 

<?php

// Name inputted by user.
$name = "   pRinCE  oF  DaRKnEsS ";

function formatName($str)
{
   // Cut out unnecessary spaces and trim.
   $parts = explode(" ", preg_replace('/\s+/', ' ', trim($str)));

   // Cycle through the names.
   foreach ($parts as $i => $val)
       $parts[$i] = ucfirst(strtolower($val));  // All to lowercase and first to capital.

   // Put our names back together and return formatted string.
   return implode(" ", $parts);
}

// Output: Prince Of Darkness
echo formatName($name);

?>

 

You usually don't want to manipulate user submitted data in that way, for the simple reason that you have no way of knowing if that's what the user wants it to look like. If you insist on doing it, perhaps you overlooked ucfirst?

I don't know for sure, but places I've seen this done it is used where people try to actually make realistic names for stuff like game characters. Sometimes it's necessary.

If you allow first & last names or possibly more, something like this could work.

 

<?php

// Name inputted by user.
$name = "   pRinCE  oF  DaRKnEsS ";

function formatName($str)
{
   // Cut out unnecessary spaces and trim.
   $parts = explode(" ", preg_replace('/\s+/', ' ', trim($str)));

   // Cycle through the names.
   foreach ($parts as $i => $val)
       $parts[$i] = ucfirst(strtolower($val));  // All to lowercase and first to capital.

   // Put our names back together and return formatted string.
   return implode(" ", $parts);
}

// Output: Prince Of Darkness
echo formatName($name);

?>

 

There are more reasons not to do it programatically than there are to do it, IMO. For instance, what happens to 'mcDonald' with that function?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.