Recipe 7.4. Formatting User-Entered Information


You need to change names, phone numbers, or other data entered through a form to match your preferred format.


Use PHP functions and/or JavaScript methods to change capitalization on words and clean up and reformat phone numbers before they are recorded for future use.

Here are the relevant PHP methods:

ucfirst( )

Capitalize the first letter in a string.

ucwords( )

Capitalize the first letter in every word in a string.

strstr( )

Get the first occurrence a string.

substr( )

Get part of a string.

ereg( )

Find a regular expression search pattern in a string.

ereg_replace( )

Search and replace function using a regular expression.

Here are similar methods for JavaScript, where string is the string variable to operate on: )

Find a regular expression search pattern in a string.

string.replace( )

Search and replace function using a regular expression.

string.toUpperCase( )

Capitalize all letters in a string.

string.toLowerCase( )

Make all letters in a string lowercase.

string.slice( )

Get part of a string.

string.concat( )

Join two strings together.


Even with properly formatted sample data adjacent to your form fields (see Recipe 7.3), you can't always count on visitors to type in their information the way you want them to. There are the lazy (or aspiring poets) among your site visitors who disdain capitalizationeven for their own names. Then there are the non-conformists who put slashes, periods, and who knows what else in their phone and fax numbers. If you want to generate mailing or call lists from information you collect online, you'll save yourself a lot of time later if you clean up the data and store it in a consistent format from the start.

You can combine some built-in JavaScript methods or PHP functions into custom functions that correct some common idiosyncrasies of user-entered information.

Capitalizing names

Use this simple PHP script to capitalize names:

 <? function formatName($name) {  if (ereg("[A-Z]$",$name)) {   $name = strtolower($name);  }  $name = ucwords($name); return $name; } ?> 

This custom PHP function gets one parameter$nameand first uses the built-in ereg( ) function to check if the user has typed his name in all caps. The search pattern [A-Z] followed by the dollar sign checks the last letter in the name to see if it's capitalized. If the name is all-caps, the built-in function strtolower( ) knocks every letter in the name down to its junior counterpart. Then the function uses the built-in function ucwords( ) to capitalize the first letter.

Writing your own functions gives you the advantage of modifying them as your needs change. For example, this function would convert the last name "o'reilly" into "O'reilly"close, but no cigar. You can add another conditional to the function that handles these types of last names:

 <? function formatName($name) {  if (ereg("[A-Z]$",$name)) {   $name = strtolower($name);  }  $name = ucwords($name); if (strstr($name,"'")) {    $name_split = split("'",$name);    $name = $name_split[0]."'";    $name .= ucfirst($name_split[1]);   } return $name; } ?> 

Here, the strstr( ) function looks for an apostrophe in the name. If so, it uses the split( ) function to divide the name into an array of two variables at the apostro-phe$name_split[0] and $name_split[1]. Then the last two new lines put $name back together: first, by appending the apostrophe back onto the front half of the name. Then by concatenating (using the .= operator) the existing $name variable with first-letter-capped version of the second half. This will cover the O'Reillys and D'Amicos, among others.

Then there are the McDonalds and McLaughlins. Without another addition to the function they will be recorded as "Mcdonald" and "Mclaughlin"also not good.

 <? function formatName($name) {  if (ereg("[A-Z]$",$name)) {   $name = strtolower($name);  }  $name = ucwords($name); if (strstr($name,"'")) {    $name_split = split("'",$name);    $name = $name_split[0]."'";    $name .= ucfirst($name_split[1]);   } if (ereg("^Mc",$name)) {    $name = "Mc".ucfirst(substr($name,2));   } return $name; } ?> 

An if statement that looks for "Mc" at the beginning of the namethe ^ character instructs ereg( ) to search from the beginningallows the function to capitalize the rest of the name that follows when the condition is met. You can use this function as a base to expand its capabilities to other types of name spellings as the need arises.

You also can use JavaScript to perform similar name manipulation. JavaScript's string-handling capabilities are more limited than PHP's, but the changes get made before the user submits the form, saving a bit of processing resources on the web server:

 <script type="text/JavaScript" language="JavaScript"> <!-- Begin function formatName(field) { if ([A-Z]$/)) {   name = name.toLowerCase();  } var name = field.value; var firstltr = name.slice(0,1); var remainder = name.slice(1); firstltr = firstltr.toUpperCase(); var newvalue = firstltr.concat(remainder); field.value = newvalue; } </script> 

The formatName function takes one parameter called field, the name of the form field to be processed. The first three lines check for users who entered their names in all caps, and, if so, convert the string to all lowercase letters. Then three variables are defined: the value of the form field (var name), the first letter of the form field value (var firstltr), and the rest of the form field value (var remainder). JavaScript has two case-changing methodstoLowerCase and toUpperCasethat, as their names imply, are all-or-nothing actions. There are no methods for capping first letters in strings or first letters in words in strings as in PHP. That limitation complicates Java-Script's ability to handle two word last names and last names with more than one capital letter, as we were able to do with PHP. Adding those abilities to this function is left to the reader.

The function should be called from the input field to be processed using the onChange event handler:

 <input name="fname" type="text" value="" size="10" maxlength="10"        onChange="formatName(this.form.fname);"> 

Fixing phone numbers

This custom PHP function takes the oddly formatted phone number a visitor might throw at your server and turns it into a plain old telephone number:

 <? function formatPhone($phone) {   $phone = ereg_replace("([[:punct:]])|([[:space:]])","",$phone);   $phone = ereg_replace("^1","",$phone);   $phone = substr($phone,0,3)."-".substr($phone,3,3)."-".substr($phone,6,4);   return $phone; } ?> 

For this function and its JavaScript counterpart, I'm assuming a North American 3-3-4 phone number format. See Recipe 7.11 for more information.

The function formatPhone( ) gets one parameter, the phone number to be converted. On the first line. the ereg_replace( ) function gets two shorthand search patterns [[:punct:]] and [[:space:]]that remove all the punctuation and spaces in the number. The second line simply removes an extraneous "1" from the beginning of the number. Then the third line rebuilds the phone number to insert hyphens between the area code, exchange, and the rest of the number.

If you'd rather have straight 10-digit phone numbers, you can leave this line out.

JavaScript matches up better with PHP for phone number reformatting than it did for name reformatting. This function, like its name reformatting counterpart, can be called from the field to be processed using the onChange event handler:

 <script type="text/JavaScript" language="JavaScript"> <!-- Begin function formatPhone(field) { var number = field.value; number = number.replace(/(\s+)/g,""); number = number.replace(/(\))/g,""); number = number.replace(/(\()/g,""); number = number.replace(/(\.)/g,""); number = number.replace(/(\/)/g,""); number = number.slice(0,3)+'-'+number.slice(3,6)+'-'+number.slice(6,10); field.value = number; } // End --> </script> 

The formatPhone function gets the name of the field as a parameter and creates a variable (number) for the field value. Then, it uses the string.replace method several times to remove spaces and unwanted punctuation from the number. Finally, the string.slice method reformats the phone number the way you want it, with hyphens.

See Also

Recipe 7.3 shows how to add sample input to a form to help your users get formatting right on their own. Recipe 7.1 ensures that fields aren't left blank (making these forms pretty useless).

Web Site Cookbook.
Web Site Cookbook: Solutions & Examples for Building and Administering Your Web Site (Cookbooks (OReilly))
ISBN: 0596101090
EAN: 2147483647
Year: N/A
Pages: 144
Authors: Doug Addison

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: