Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi all,

I'm still working on the postal code issue, for Canada at the moment and  
I'm still stuck.

I've decided to try:
= See if it's alpha-numeric
= Create an array
    = See if there is a space where it belongs
    = Validate for digits in proper positions
    = Since it's alpha-numeric, the 3 characters left must be Alphabetic.
     If the validations work, keep going.
     If not, halt & allow for a re-entry.

The ctype statement will NOT work in any form and throws various errors  
regardless of wher I place it or what I use s the var. Remove the entire  
ctype, and everything works again.

In code, this equates to, as best as I can:
IF(strlen($zip) === 7) {
    echo "Zip appears to be Canadian . <br />";
    // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
*    if (ctype_alnum(str_split($zip,1)) {   <---- Throws error [1]
*    echo "Is Alpha Numeric.";

            // ================ LET'S ASSIGN IT TO AN ARRAY
        echo ' <pre>';
       echo '</pre>';        
          // ================= check space where it belongs
        if($zip[3] === " ") {
        echo "Space in correct place<br />";

[1] : Error is:
Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\twa1.php on  
line 107
Line 107 is:
    echo "Zip appears to be Canadian . <br />";
I have tried various forms of the ctype statement, where it's shown here  
and lower in the code after the array is generated, and using $zip[0] .  
$zip[3]... etc. I simply can not get any form of the ctype statement  
working and I have a LOT of sample code I've collected from several  
sources, all not quite what I need.

If I change the code & location as follows:
IF(strlen($zip) === 7) {
    echo "Zip appears to be Canadian . <br />";
    // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC     

            // ================ LET'S ASSIGN IT TO AN ARRAY
        echo ' <pre>';
       print_r(str_split($zip,1)); <--------------- LINE 114
       echo '</pre>';

            if (ctype_alnum(($zip[0]))
     echo "Is Alpha Numeric.";    
          // ================= check space where it belongs
        if($zip[3] === " ") {
        echo "Space in correct place<br />";
It still throws an error as:    
Parse error: syntax error, unexpected T_ECHO in C:\xampp\htdocs\twa1.php  
on line 114

What the heck am I doing wrong? Any advice appreciated; I can't believe  
I can't get ctype to work; it seems so simple!




Quoted text here. Click to load it

After a previous thread in which several people pointed out your
unbalanced parens, followed by suggestions about how you might
systematically discover such elementary errors, followed by
discussions about editors that could point these out and in which YOU
yourself recommended one that does this,  

how is it that you are still posting code like this?


On 2013-08-25 2:21 PM, Richard Yates wrote:
Quoted text here. Click to load it

OmiGod, I didn't see that and looked over & over & ...!

Actually, I found the method I'm now using by perusing those old threads  
and have managed it, finally.

I have nothing useful to contribute here, so ... that's what I'm doing.  
Sorry if it irks you; but that's called "life". When one has nothing  
useful to say, that's exactly what they should say: Nothing.


Quoted text here. Click to load it

Try this:

function TwaynesParens($mycode) {
    $rightparens=substr_count($mycode, ')');
    if($leftparens==$rightparens) {  
        echo '<br />Good for me! The problem is not unblanced
parens in my code (for once.)';
           } else {  
        echo '<br />I did it again.<br />DO NOT POST THIS CODE


On 25/08/13 19:51, Twayne wrote:
Quoted text here. Click to load it

I assume you have just added the '*' first in the line to show which  
rows you are talking about.

Simple maths will show your error, lets count your opening parentheses

if (ctype_alnum(str_split($zip,1)) {
    1           2         3

and now the number of closing parentheses

if (ctype_alnum(str_split($zip,1)) {

So we get 3 opening parenthesis and 2 closing, this is what the "Parse  
error: syntax error, unexpected '{'" is about, you need to close all  
your parentheses.

You know you will end up with loads of if cases if you keep on doing  
this instead of using a regular expression, this would speed it up and  
make your code a lot easier to read (case insensitive):

if(preg_match("/^[a-z]\d[a-z] \d[a-z]\d$/i",$postcode)) {
         // this could be a valid Canadian postcode
    // just add what you need to do to check it against
    // Canadian Post, worst case use the "Find a post office"




On 2013-08-25 2:38 PM, J.O. Aho wrote:
Quoted text here. Click to load it


So Richard noted also. I even fired up another editor that shows parens  
et al by simply hoering a mouse over the tag. Damned if I didn't see it  
there either!
Quoted text here. Click to load it

It's so clearly visible to me now; no idea why I couldn't see it before.
Quoted text here. Click to load it

I agree with you but I'm not useing regular expressions. 1 they're never  
clear to me, 2 I'm trying to avoid them as I have a couple in other  
cases where they actually cause noticeable slow-downs on even my Local  
Server, and magnitudes worse with I upload them to be "live", 3 there  
are so many ways to do the same thing in PHP my goal is to learn them  
and take notes of the most useful.
    So it's not just learning to code properly, it's also to learn  
better, less-code ways of doing things.

If you're so inclined you won't miss anything if you don't read the  
following but it might be well to explain a couple of things about the  
real reasons I'm having so much trouble here.

Mainly, I've been disabled and "retired" since 1994. In 2002 I suffered  
a serious brain concussion and lost many memories plus any ability w/r  
to Short Term Memory. I was even labeled "learning impaired" due to the  
concussion.  My doctor advised me that I might be able to get some of my  
old memories back, along with kicking the "learning disabled" tag, by  
"exercising" my brain.  He suggested since I liked computers that I find  
a way to use them to exercise the ol' gray matter.
     Currently I've regained most of my old memories and an no longer  
considered "learning disabled", but handling short-term memory issues is  
a real fight. IFF I handle them properly, I am able to retain memories,  
but it's often thwarted by not remembering to take the notes I need or  
otherwise record the information. That, on top of my disabilities (3  
types of arthritis, several myalgias and other sundry things, make it  
hard.  So, when I thought I was ready a few months ago, I decided to  
take on either VB net again, or PHP, both of which I knew at one point  
in time. I chose PHP because I did have some websites to my credit, and  
used a lot of old PHP code (well it's old now), so my overall goals now  
are to get to know PHP well enough to use it and also participate with  
responses on groups and forums such as this one.  And besides, VB code  
is expensive <g> since I was unable to work.

I don't give up easily and "Patience and Perseverence" is my mantra  
these days. It actually works! lol

I dislike saying all those things about myself, but I think it's fair to  
mention them as part of my gratitude for this group and several others.




Quoted text here. Click to load it
Quoted text here. Click to load it

For things that come up repeatedly, posting a short reminder can be
helpful. I have taped to my monitor a note that says '=' !==  


On 2013-08-25 4:16 PM, Richard Yates wrote:
Quoted text here. Click to load it

lol, I hear you there! I think I've been Post-It's major income! That's  
actually why now I use NoteTab Pro; I have their PHP and SQL libraries  
and clips, plus created my own abbreviated clip for often used  
statements. They make it easy to create your own clip libraries. It has  
a section for "learned" and one for "new" statements, both of which are  
complete with formatting, such as:

A complete Form start set of code, with or without the html, body, div,  
End form, body, html, and optionally <div> tags.
$ = check_input("$");  [one of several functions ]
<br />
"<br />"
." <br />
autofocus =  "autofocus"

to mention just a few of them at random.
    They save a tremendous amount of typing for me, meaning less time to  
forget something during the process of coding, even though I'm a  
touch-typist, and I try hard to use a lot of comments.

Where I get in trouble is when I have to go back and edit for whatever  
reason, and lose a parens or curly bracket in the process. And when I  
get tired without realizing it I manage to compound those errors. e.g.  
I'll add something that appears to work, and then a few tests later  
added something where the earlier error became obvious.Fortunately I  
like coding and am always after ways to  help myself but ...

I also occasionally use NotePad++ too; it automatically displays tag  
matching by just hovering the mouse over one.
     Both NoteTab & NotePad++ know when a file they have open has been  
modified and won't let you do anything until you tell it to reload or  
keep what it has in memory. The two are competitively equal except  
NotePad doesn't seem to have any capability to create libraries or code  

I have other apps but none (yet) that come close to NoteTab Pro. IMO, at  




Twayne wrote:

Quoted text here. Click to load it

If you're having problems keeping *nesting* parens balanced, you might
consider to avoid them.  The code above could be written this way:

  $characters = str_split($zip, 1);
  $is_alphanumeric = ctype_alnum($characters);
  if ($is_aphanumeric)

This has the additional advantage that it eases debugging.

BTW: The code won't work, as ctype_alnum() expects a string, but
str_split() returns an array.

Christoph M. Becker


On 2013-08-25 4:19 PM, Christoph Michael Becker wrote:
Quoted text here. Click to load it

Agreed & understood.
Quoted text here. Click to load it

Wish my code snippet hadn't been snipped, because it did work, without  
the parens issue.
    $var was intended to be used in some places and $var[n] in others  
but I don't.
That said, I'll have a relook again as you might have a point; alnum  
still isn't giveing me what I need and I've assued it's been because of  
a necessary space in the string, which I thought I'd taken proper care of.

Thanks for the prods.



On 2013-08-25 21:28, Twayne wrote:
Quoted text here. Click to load it

Your original question was answered, but it seems you have a few
misconceptions about regular expressions. If you into learning how to do
things properly, you shouldn't dismiss them out of hand.

ad 1) "they're never clear to me"

That's a fair point, as regexes can quickly become hard to read. There's
a way around that, however: the /x modifier. Take for example the regex
in the post you replied to (just as an example, I'm not judging its
correctness for now):

   preg_match("/^[a-z]\d[a-z] \d[a-z]\d$/i", $postcode)

This can also be written as

  $regex = '/
    ^              # anchored at the start of the string
    [a-z]          # one letter a-z
    \d             # one digit 0-9
    [a-z]          # one letter a-z
    \s             # one character of white space *
    \d             # one digit 0-9
    [a-z]          # one letter a-z
    \d             # one digit 0-9
    $              # anchored at the end of the string

  preg_match($regex, $postcode)

Much easier to understand this way, especially if you're starting out
with regular expressions. That's all one string - all the white space
and the comments are ignored. (Talking about white space, a more exact
way to match "one space character" would be "[ ]").

ad 2) "they're too slow"

That may have been true in other languages and many, many years ago, but
it's certainly not the case with PHP today. This regex runs over 2
million times per second on a single core of my middle-aged laptop. It
should be more than fast enough, considering I could check every
Canadian's zip code in under 15 seconds with it... I don't know what
you're building, but I can guarantee that this won't be the reason for
any noticeable slow-downs.

ad 3) "there are many other ways"

True, but the regex is by far the shortest. It's also what most
programmers would expect to see in this situation. It is, as you say, a
"better, less-code" way to do it.


Quoted text here. Click to load it

I found it interesting to read.



Fiver wrote:

Quoted text here. Click to load it

JFTR: This applies to *Perl* and *Perl-compatible* regular expressions  
(PCRE) only.  PHP also supports POSIX Extended REGular expressions (ERE)  
that do not have that feature.  However, the POSIX ERE functions (ereg*())  
are deprecated since PHP 5.3 in favor of the PCRE functions (preg_*()).

PHP also supports commenting in PCRE like so:

  $regex = '/'
         . '^(?#      anchored at the start of the string)'
         . '[a-z](?#  one letter a-z)'
         . '\d(?#    one digit 0-9)'
         . '[a-z](?#  one letter a-z)'
         . '\s(?#    one character of white space)'
         . '\d(?#    one digit 0-9)'
         . '[a-z](?#  one letter a-z)'
         . '\d(?#    one digit 0-9)'
         . '$(?#      anchored at the end of the string)
         . '/ix';


(In this case, I would pick the PCRE_EXTENDED variant, too.  “(?#…)” is  
better suited for short inline comments.)

Another way, which can be combined with either one, is to use another  
delimiter.  For example, attempting to match an “http:” URI with


is safe, but rather hard to read.  It can be written better readable as


or, with PCRE_EXTENDED enabled,

  '! http:// (?:[^/\s]+) /? !x'

This can be further simplified to

  '! http:// (?: .+?) /? !x'

and even inline-commented as suggested above (“#” changed to “!” because of  
unescaped “#” delimiting single-line inline comments).
Quoted text here. Click to load it

Or simply " ".  The character class has the slight advantage over the simple  
assertion that it does not matter how many spaces you write between the  
brackets.  However, character class building might prove to be more  
expensive than the simple assertion, and even if it looks as if there are  
only spaces in-between, a tab character or another non-breaking whitespace  
character could have slipped in – a bug waiting to happen that is easily  
spotted with the simple assertion (it just does not match then).
Quoted text here. Click to load it

It is still true that regular expressions are (or can be) comparably  
expensive with regard to runtime and memory usage, which is why some (non-
PHP) runtime environments disable them by default for security reasons.  
However, if you are using regular expressions for *pattern* matching, the  
program will likely run faster than if you had used plain string operations.  
Because the native machine code (of PHP) has been optimized for that  

(Rule of thumb: Explicitly prevent regular expressions from becoming too  
greedy even though in the end they would not match more than they should.  
And do not capture what you do not want to process.  It is *unnecessary*  
backtracking and capturing that makes regular expressions more expensive  
than they could be.)

For example,

  preg_match('/foo/', 'foobar') > 0

has no advantage over

  strpos('foobar', 'foo') !== false


  preg_match('/\bfoo/u', 'foobar') > 0

has as it matches “foo” only at the *start* of a *Unicode* word.

It should also be noted that (Perl-compatible) regular expressions are  
included in one of the ten areas you need to be knowledgable in (“Strings &  
Patterns”), in order to pass the Zend Certified Engineer PHP 5.3 test:


When all you know is jQuery, every problem looks $(olvable).


On 26/08/13 09:25, Thomas 'PointedEars' Lahn wrote:
Quoted text here. Click to load it
I've been coding PHP for about 5years now and C/Unix/linux for over 30
and I have never ever found it worthwhile using complex regexps.

There is always a simpler way to do it.


(in-ep-toc’-ra-cy) – a system of government where the least capable to lead are elected by the least capable of producing, and where the members of society least likely to sustain themselves or succeed, are rewarded with goods and services paid for by the confiscated wealth of a diminishing number of producers.


On 2013-08-26 4:29 AM, The Natural Philosopher wrote:
Quoted text here. Click to load it

You, Fiver and Thomas all have strong backgrounds compared to mine, I'm  
sure. It's not that I have an aversion to regex on any solid opinions of  
my own, but a lot of material I've read and committed to disc, from both  
aged and current opinions, suggest regex isn't the best way to go.
   So I checked with my remote server support folks and they also wish a  
lot of people would stop using regex type patterns as they're  
time-intensive, more so than the alternatives. But at the same time they  
say they'll never ask a customer to NOT use them as they have plenty of  
cpu time available. So it wasn't exactly definitive, but at least they  
did make the comments for me. oh; it was a phone call for what that's  
worth, not support e-mail. I have several websites parked there too so I  
get free extended support.

At any rate, since regex types are like learning another language for  
me, I'm happy to rationalize that I'm doing the right thing by not using  
them. Also, a lot of the newer things added to PHP's latest versions,  
many seem to be aimed at being able to work without using regex type things.




On 08/25/2013 01:51 PM, Twayne wrote:
Quoted text here. Click to load it

   I don't understand why you're not using the regex that does away with  
all that code.

$canadian_regex =  
$zip = "A2B 3X4";

IF (preg_match($canadian_regex,$zip)) {
   echo "Zip is Canadian\n";
} else {
   echo "Zip is not Canadian\n";


$usa_regex      = "/[0-9](-[0-9])/";
$canadian_regex =  


$isUSA      = (preg_match($usa_regex,$zip)) ? TRUE : FALSE;
$isCanadian = (preg_match($canadian_regex,$zip)) ? TRUE : FALSE;


// by country ISO

$postal_code['US'] = "/[0-9](-[0-9])/";
$postal_code['CA'] =  
$postal_code['VI'] = "/008[0-5]1/";

$isUSA           = (preg_match($postal_code['US'],$zip)) ? TRUE : FALSE;
$isCanadian      = (preg_match($postal_code['CA'],$zip)) ? TRUE : FALSE;
$isVirginIslands = (preg_match($postal_code['VI'],$zip)) ? TRUE : FALSE;


Registered Linux user #461062
-Have you been to www.php.net yet?-


Quoted text here. Click to load it

Personally I avoid regexps like the plague as they tend to be  
write-only. My take is that if I'd wanted to do line-noise, I'd be using  
TECO as an editor instead of TextWrangler.


"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted"  --  Bill of Rights 1689


If anyone is interested, here's the code I ended up with.  It still  
needs to validate alphabetic & numeric array positions but that should  
be reasonably simple to add by checking the array positions for alpha or  
digit characters.

Thanks for all the help!
$zip = check_input($zip);
$zip = strtoupper($zip);
if(strlen($zip)===5) {
    echo "U.S. postal code used "; }
    IF (is_numeric($zip)) {
    echo " and is 5 digits.";
    IF(strlen($zip) === 7) {
    echo "Zip appears to be Canadian . <br />";
    // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC

            // ================ LET'S ASSIGN IT TO AN ARRAY
        echo ' <pre>';
       echo '</pre>';
                  // ================= check space is where it belongs
        if($zip[3] === " ") {
        echo "<br />Space in correct place<br />";
$sUser = $zip;
$aValid = array(' ');
if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
        echo "Username has a problem";
     echo 'Your Postal Code is NOT properly formatted.';
else {
echo "Postal code is properly formatted as ALPHA NUMERIC with ONE SPACE  
as the 4th character";


On 2013-08-25 21:35, Twayne wrote:
Quoted text here. Click to load it

For the US zip codes:

is_numeric() is not the correct function to use here. "+.1e1" and
"0xCAB" are both numeric strings and would pass as US zip codes.
Better solution:

  if (strlen($zip) == 5 && ctype_digit($zip)) {
      echo "looks like a US zip code\n";

Better yet: check for known bad zip codes as well

  ... && $zip != "00000" && $zip != "99999" && I don't know, some more

For the Canadian zip codes:

Your code has a comment "let's assign it to an array", and you also
wrote that you still needed to validate the array positions, but you
never do create an array (except for the unnecessary one in $aValid,
which should probably be a string).

Anyway, you're right that you still need to check the characters to the
right and left of the space, or strings like "x      " and "     3 "
would be seen as valid zip codes. Here's one way to do it:

  if (strlen($zip) == 7
      && $zip[3] == " "
      && ctype_alpha($zip[0] . $zip[2] . $zip[5])
      && ctype_digit($zip[1] . $zip[4] . $zip[6]))
      echo "looks like a Canadian zip code\n";

Note the two closing parens after $zip[6] ;)


PS: No regexes were killed or injured in the production of this message.


On 26/08/13 19:07, Fiver wrote:
Quoted text here. Click to load it

Now key in SW1A 1AA as a postcode and see what it does with it.

there is a world beyond north America.


(in-ep-toc’-ra-cy) – a system of government where the least capable to lead are elected by the least capable of producing, and where the members of society least likely to sustain themselves or succeed, are rewarded with goods and services paid for by the confiscated wealth of a diminishing number of producers.


On 2013-08-26 21:19, The Natural Philosopher wrote:
Quoted text here. Click to load it
Quoted text here. Click to load it

Quoted text here. Click to load it

It won't be recognized as a Canadian zip code, which is as it should be.

Quoted text here. Click to load it

Meh, that's just a rumor.
And even if there is, I heard that there be dragons.

The question was about US and Canadian zip codes, so what's your point?


Site Timeline