tags:

views:

231

answers:

3

Hey all, I have a file that contains a mish-mash of cities, states, and zip codes. Example:

Munson 11010 Shelter Island Heights. . . .. 11965 Brentwood 11717 Halesite 11743

I need to grab all of the zip codes out of that text. They are only 5 digit (no 5+4), and there are no other numbers besides the zips. It seems like a pretty straightforward regex thing, but I have no idea at all how to make the expression.

I know some PHP so that's my preferred language, if possible. Ideally I'd like it to display the output 1-zip-per-line so that I can copy/paste into something like Excel.

Thanks for any help!

+3  A: 
preg_match_all('[^0-9]([0-9]{5})[^0-9]', $input, $out);
foreach($out as $val)
    echo $val[1] . "\n";
Cody Brocious
You're a brave one for venturing into PHP again after all those years.... :-P
Chris Jester-Young
According to the OP, there's no need to bracket the regex, but if I were doing it I would use word boundaries -- '/\b\d{5}\b/' -- or -- lookarounds -- '/(?<!\d)\d{5}(?!\d)/'. Also, you forgot the regex delimiters (ie, the forward-slashes in my regexes).
Alan Moore
A: 

The following code should send you in the right direction:

<?php
$str = 'Munson 11010 Shelter Island Heights. . . .. 11965 Brentwood 11717 Halesite 11743 ';

preg_match_all("/\d{5}/", $str, $matches);

print_r($matches);
?>
Fluff
A: 

Great! Thanks so much -- here's what I ended up using:

preg_match_all("/\d{5}/", $input, $matches);

foreach($matches[0] as $zip){
    echo $zip.'<br/>';
    };