Reputation: 2208
I am trying to get zipcodes out of address strings.
Zipcodes may look like this: 23-123
or 50-530
.
Strings usually look like this: Street 50, 50-123 City
What I tried to do is finding the position of the zipcode and cut the next 6 characters starting from that point. Unfortunatelly strpos returns false all the time.
$zipCodePosition = strpos($form->address, "\d{2}-\d{3}");
$zipCode = $zipCodePosition ? substr($form->address, $zipCodePosition , 6) : '';
Upvotes: 0
Views: 193
Reputation: 626794
The strpos
does not allow the use of regex as an argument.
You need a preg_match
/ preg_match_all
here:
// Get the first match
if (preg_match('~\b\d{2}-\d{3}\b~', $text, $match)) {
echo $match[0];
}
// Get all matches
if (preg_match_all('~\b\d{2}-\d{3}\b~', $text, $matches)) {
print_r($matches[0]);
}
The regex matches
\b
- a word boundary\d{2}
- two digits-
- a hyphen\d{3}
- three digits\b
- a word boundarySee the regex demo.
Upvotes: 2