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.
mwheeler_fsdAsked:
Who is Participating?
 
snoyes_jwCommented:
<?php
$addr = array("PO 123", "PO BOX 123", "P.O. BOX 123", "BOX 123");
print_r(preg_grep("/((P\.?O\.?(B\.?)?(\s+Box)?)|(Post\s+Office(\s+Box)?))\s*#?[0-9]+/i", $addr));
?>

matches:
Array
(
    [0] => PO 123
    [1] => PO BOX 123
    [2] => P.O. BOX 123
)
0
 
snoyes_jwCommented:
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.
0
 
snoyes_jwCommented:
You'll probably want to make it case insensitive.  Add the letter "i" between the last / and closing "
...#?[0-9]+/i", $addr, $regs);
0
 
mwheeler_fsdAuthor Commented:
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?
0
 
snoyes_jwCommented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.