Thursday, August 16, 2012

Cleaning phone number data from database

I have been working with a database where the phone number data is very dirty.  People have been imputing numbers any old way so I wrote this to clean the data as it comes into the form. It strips out anything that is not a number and removes the '1' at the beginning of the number.
<?php

    private function CleanPhone($ph)
    {
        //break the string into an array
        $phSplit = str_split($ph);
        //Initialize the return value
        $nph = "";
        //Check each item in the array
        foreach($phSplit as $k => $n)
        {
            //if its numeric add it to the return value
            if(is_numeric ($n))
            {
                //if the first number is not a 1 add it to the retun value
                if($k == '0')
                {
                    if($n != '1')
                    {
                        $nph = $nph.$n;
                    }
                }
                else
                {
                    $nph = $nph.$n;
                }
            }
        }
        return $nph;
    }


$nph = CleanPhone($phoneFromDatabase)


$ph1code = substr($nph,0,3);
$ph1pre = substr($nph,3,3);
$ph1suf = substr($nph,6,4);
                   
$ph = "
<div>
          <div>Phone Number</div>
          (<input id='ph1code' name='ph1code' size='3' maxlength='3' type='text' value='$ph1code' form=' Form' />)
           <input id='ph1pre' name='ph1pre' size='3' maxlength='3' type='text' value='$ph1pre' form=' Form' /> -
            <input id='ph1suf' name='ph1suf' size='4' maxlength='4' type='text' value='$ph1suf' form='Form' />
             </div>
                    ";
?>

And here's how it fits on the site.

<html>
<body>

<?php echo $ph; ?>
<form name='Form' action='index.php' method='post'></form>
</body>
</html>

No comments:

Post a Comment