Joining 2 preg's into 1 ... (Simple I think)

Discussion in 'PHP' started by pepe_lepew1962, Dec 21, 2008.

  1. #1
    Hello;

    I have the below code that works perfectly. It checks the vaildity of either a US Zip or Canadian postal code. I am trying to add them together and I am having problems with the "AND" portion. Below is the working code and the bottom is what I am trying without success. Can anyone help with the bottom part please.

    // This works and I want to combine the 2 preg's together.
    $seq[0] = preg_match("/^\d{5}$/", $_POST["zip"]);
    $seq[1] = preg_match("/^([A-CEGHJ-NPR-TV-Z]){1}[0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[ -][0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[0-9]{1}$/i",$_POST["zip"]);

    if(($seq[0] === 0) && ($seq[1] === 0))
    $errZip = '<class="errText">Invalid Zip/Postal code';

    // This is my failed attempt
    if(preg_match("/^\d{5}$/", $_POST["zip"] === 0) && (("/^([A-CEGHJ-NPR-TV-Z]){1}[0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[ -][0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[0-9]{1}$/i",$_POST["zip"] === 0))
    $errZip = '<class="errText">Invalid Zip/Postal code';

    PS: The reason for me wanting them together is that all my preg matchs are 1 liner's and is both visually similar and easier to write comments about.
     
    pepe_lepew1962, Dec 21, 2008 IP
  2. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Well, it's pretty obvious why it fails.. Couple things wrong with that IF. :|


    if(preg_match("/^\d{5}$/", $_POST["zip"]) === 0 && preg_match("/^([A-CEGHJ-NPR-TV-Z]){1}[0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[ -][0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[0-9]{1}$/i",$_POST["zip"]) === 0)
      $errZip = '<class="errText">Invalid Zip/Postal code';
    PHP:
    That should work. That's not really combining the two preg calls into one but it's making it all just one if statement.. I *think* you can combine them into 2 this way, though:

    if(preg_match("/^((\d{5})|(([A-CEGHJ-NPR-TV-Z]){1}[0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[ -][0-9]{1}[A-CEGHJ-NPR-TV-Z]{1}[0-9]{1}))$/", $_POST["zip"]) === 0)
      $errZip = '<class="errText">Invalid Zip/Postal code';
    PHP:
    You'll have to test it.
     
    zerxer, Dec 21, 2008 IP
  3. pepe_lepew1962

    pepe_lepew1962 Member

    Messages:
    36
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    zerxer, awesome !!!
    The first segment rocks. Having problems with the second bit.
    Thank you.
     
    pepe_lepew1962, Dec 21, 2008 IP
  4. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yeah, I wasn't sure if the second would work, so it's best to just leave it as one if statement instead of trying to merge the two pregs into one. First one is fine how it is.
     
    zerxer, Dec 21, 2008 IP