PHP Regular Expression Issue

Posted on 2012-08-17
Last Modified: 2012-08-17
My following regular expression is causing an Unknown modifier '|' error.

preg_match '(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)', $this);

Open in new window

It's suppose to validate either US or Canadian postal codes.

Anyone know why the | conditional is not functioning (or any other code error)?

Question by:christamcc
    LVL 30

    Accepted Solution

    Try to modify it ths way:

    preg_match '#(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)#', $this);

    Author Comment

    Thanks marqusG, it worked!  I'm going to Accept your solution, but can you let me know one thing?  Is the "#" pretty much the required deliminator when working with the 'or' conditional?
    LVL 30

    Expert Comment

    by:Marco Gasi
    Not exactly: you have to use something sign is not used in regex and in your regex you didn't use anything. You would had just used '/'

    preg_match '/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/', $this);

    or something else. The most used delimiter are '#' and '/'.

    LVL 30

    Expert Comment

    by:Marco Gasi
    In my opinion, the best site to learn about regular expressions is RegExBuddy (


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive Gives IT Their Time Back

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
    Part of the Global Positioning System A geocode ( is the major subset of a GPS coordinate (, the other parts being the altitude and t…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now