Hey everyone,
I've been working on a small project in PHP and I need to validate a street address using a regular expression. I'm quite new to regular expressions, so I'm a bit confused about how to go about it.
Basically, I want to make sure that the street address follows a specific format. It should include the house number, street name, and optionally the apartment or unit number. The street name can contain alphabets, numbers, spaces, and some special characters like hyphen and comma.
Here are a few examples of valid street addresses that I want to match:
- 123 Main Street
- 456 Elm Street, Apartment 7
- 789 Oak Avenue, Unit #2
And here's an invalid address that I want to exclude:
- 10 Pine St. - this format is not allowed
I believe I can achieve this using the preg_match function in PHP, but I'm not entirely sure about the regular expression pattern I should use. I want to make sure it's flexible enough to handle different address formats, yet strict enough to avoid matching invalid addresses.
Any help or guidance on this would be greatly appreciated! Thank you in advance!

Hey there!
I've had a similar experience with validating street addresses using regular expressions in PHP. It's a bit tricky, but I managed to come up with a pattern that worked well for me.
For validating the street address format you described, you can use the following regular expression pattern:
Let me explain the parts of this pattern:
- `^\d+` ensures that the address starts with one or more digits representing the house number.
- `\s` matches a single space after the house number.
- `(?:[a-zA-Z0-9\s\-]+)` matches the street name, allowing alphanumeric characters, spaces, and hyphens.
- `(?:,\s(?:Apartment|Unit)\s(?:(?:#|)\d+))?` makes the apartment or unit number optional. It matches a comma followed by a space and the terms "Apartment" or "Unit" (case insensitive) and an optional pound symbol (#) followed by one or more digits.
You can then use the `preg_match($pattern, $address)` function to check if a given address matches this pattern.
I hope this helps! Feel free to ask if you have any further questions or hit any roadblocks. Best of luck with your project!