Stripping Unwanted Characters
| From: | Robert Miller | Date: | Fri, 23 Nov 2001 19:01:51 +0000 |
| Subject: | Stripping Unwanted Characters | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-75600@lists.php.net to get a copy of this message | ||
I'm posting this (see below) for two reasons: 1. so that others may benefit, and 2. to invite
feedback on my code (PHP is the first language I have learned... and I've only been doing this
for a week or so).
Cheers, Rob
P.S. Has anyone found a good way to parse variables to validate specific formats? For example:
Canadian postal codes (ZIP codes) are like A1A-1A1. Driver's Licences are A123456789.
Problem:
Unwanted characters are often added by users of web based forms. This causes problems when storing
the data, especially given the constraints of a database such as MySQL.
Solution:
Evaluate each variable, character by character, and (if true) add it to a new variable which may be
used.
<?
include("supercln.inc");
$sHomePhone = supercln("num",$frmHomePhone);
$sProvince = supercln("alpha",$frmProvince);
?>
<?
// This is the supercln.inc file included in the first section of PHP code.
function supercln($clntype, $clninput) {
$strcount = strlen($clninput);
if ($clntype == alpha) {
for ($i = 1; $i <= $strcount; $i++) {
$strletter = $clninput{$i-1};
if ( preg_match("/[A-z]/",$strletter) == true ) {
$strcleaned = $strcleaned.$strletter;
}
}
}
elseif ($clntype == num) {
for ($i = 1; $i <= $strcount; $i++) {
$strletter = $clninput{$i-1};
if ( preg_match("/[0-9]/",$strletter) == true ) {
$strcleaned = $strcleaned.$strletter;
}
}
}
elseif ($clntype == alphanum) {
for ($i = 1; $i <= $strcount; $i++) {
$strletter = $clninput{$i-1};
if ( preg_match("/\w/",$strletter) == true ) {
$strcleaned = $strcleaned.$strletter;
}
}
}
else {
$strcleaned = "Error... must be either alpha num or alphanum.";
}
return $strcleaned;
}
?>