quasi random (kaolinfire) wrote,
quasi random
kaolinfire

cheap thrills

I don't know why, but adding notes to php.net is one of the biggest thrills for me, of late. I'm giving something back. I'm showing off. I'm putting myself up for rejection. So far, I'm just ignored. But I'm not giving up! First bit of code went up, well, if you were paying attention you saw it. I don't remember. Aha! Oct 17. I'm actually recording these things, now -- http://erif.org/code/php.php

Oops! I never posted about it, then. Silly me. Well, check out the link above if you want to see the other super-craziness =)

Today's code:


test for valid US phone number, and get it back formatted at the same time

  function getUSPhone($var) {
    // area code
    $US_PHONE_PREG ="/^(?:\+?1[\-\s]?)?(\(\d{3}\)|\d{3})[\-\s\.]?"; 
    // seven digits
    $US_PHONE_PREG.="(\d{3})[\-\.]?(\d{4})"; 
    // any extension
    $US_PHONE_PREG.="(?:\s?x|\s|\s?ext(?:\.|\s)?)?(\d*)?$/"; 
    if (!preg_match($US_PHONE_PREG,$var,$match)) {
      return false;
    } else {
      $tmp = "+1 ";
      if (substr($match[1],0,1) == "(") {
        $tmp.=$match[1];
      } else {
        $tmp.="(".$match[1].")";
      }
      $tmp.=" ".$match[2]."-".$match[3];
      if ($match[4] <> '') $tmp.=" x".$match[4];
      return $tmp;
    }
  }



usage:
  $phone = $_REQUEST["phone"];
  if (!($phone = getUSPhone($phone))) {
    //error gracefully :)
  }


Tags: php, validation
Subscribe

  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 6 comments