Page 1 of 1

Parsing and matching with REGEX

Posted: Thu Oct 22, 2009 10:21 pm
by alex.barylski
I have the following simple RE for matching Canadian post codes:

Code: Select all

define('POST_CODE', '/[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d{1}/');
Simple but it's not returning any array of interest. I finally figured out it's probalby because there are no () around each section that I want parsed out???

I am using REGEX like this to facilitate my validation library. Ideally I would like the result of each operation to return the array of parts extracted using REGEX.

Is there any way to accomplish this, BUT, including a name with the array elements, so what is returned is:

Code: Select all

array
(
  ['FSA'] => 'R'
)
FSA is the first character of a post code, the rest should be matched, but only the first character returned in the results as it's what is of interest, after the regex has determined the format of the post code is complete and valid.

Another issue I have with the above regex defined in POST_CODE is the fact that values like:

R2R1R2 => NO Match
R2R 1R2 => Match
R2R 1R22 => Still Match

The latter is what confuses me, how do make the regex stop matching at this point? Obviously the last is not valid.

I'm using preg_match -- should I use preg_match_all??? What is the difference? One is greedy? I thought that was indicated via a modifier?

Cheers,
Alex

Re: Parsing and matching with REGEX

Posted: Fri Oct 23, 2009 3:23 am
by papa
Took just a quick look:

/[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d{1}$/

Regarding the space issue. You can always trim the input before regexp.

I can have another go at it later today if help still needed.

edit:

Don't know if this helps:

Code: Select all

 
<?php
define('POST_CODE', '/([ABCEGHJKLMNPRSTVXY])\d[A-Z][ ]*\d[A-Z]\d{1}$/');
 
$subject = 'R2R1R2';
 
preg_match(POST_CODE, $subject, $matches);
 
print_r($matches);
?>
 
Don't know how to change the array keys though. I would loop through my results and create a new array.