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) : '';
Advertisement
Answer
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('~bd{2}-d{3}b~', $text, $match)) { echo $match[0]; } // Get all matches if (preg_match_all('~bd{2}-d{3}b~', $text, $matches)) { print_r($matches[0]); }
The regex matches
b
– a word boundaryd{2}
– two digits-
– a hyphend{3}
– three digitsb
– a word boundary
See the regex demo.