Link to home
Start Free TrialLog in
Avatar of mwheeler_fsd
mwheeler_fsd

asked on

Regular Expression to Capture PO Box using PHP

I need to determine if an address text input field contains a PO BOX or any derivative of PO BOX - PO, BOX, P.O. BOX, etc. I have found many good solutions on this site using JavaScript, however, I really must do this with PHP. I have been experimenting with preg_grep(), as it appears this is the best function. However, my regular expressions are sorely lacking and it has become very frustrating and I've spent a great deal of time trying to figure this out. I am inserting some code I have been working with to try and cover all the PO Box possiblities. I simply can't get it to work.

$result=preg_grep("/((P\.?O\.?(B\.?)?(\s+Box)?)|(Post\s+Office(\s+Box)?))\s*#?[0-9]+/", $addr, $regs);

This is a derivative of one of the solutions I found in the JavaScript area.

I am a new member and this is my very first post. It was my intention follow etiquette. Please let me know if I have stepped out of bounds.

Thanks in advance.
Avatar of snoyes_jw
snoyes_jw
Flag of United States of America image

preg_grep is intended for arrays, not strings.  Use preg_match instead.

I haven't picked apart the regexp, but it looks like it might work.
You'll probably want to make it case insensitive.  Add the letter "i" between the last / and closing "
...#?[0-9]+/i", $addr, $regs);
ASKER CERTIFIED SOLUTION
Avatar of snoyes_jw
snoyes_jw
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mwheeler_fsd
mwheeler_fsd

ASKER

Thank you snoyes_jw - one quick question: You had commented that preg_match() might be more appropriate the preg_grep() because the address I am checking is actually just a string - is one better then the other?
preg_match is designed to check strings, so that's what you should use.  In the example, I was checking an array to show that it worked on several different strings, so I used preg_grep.