7.4. Formatting User-Entered Information

Problem

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

Solution

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:

string .search( )

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.

Discussion

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 capitalization—even for their own names. Then there are the non-conformists who put slashes, periods, and who knows what else in their ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.