Reputation: 327
I faced a strange situation. I'd like to get ZIP code from address and my regex
\b(\w+)\b[^\w]\p{L}+$
works in sandbox https://regex101.com/r/rnjecA/1 but with the same text it's not working in PHP https://sandbox.onlinephpfunctions.com/c/3eb95 What's the matter is here?
Upvotes: 0
Views: 38
Reputation: 627100
You can use
$str = <<<AAA
County Road 99
Sauk Centre, Minnesota 56378
USA
AAA;
if (preg_match('~(\w+)\R\p{L}+$~u', $str, $m)) {
print_r($m);
}
// => Array( [0] => 56378\nUSA [1] => 56378 )
See the PHP online demo.
If you do not need the whole match and just need the ZIP as output, replace the pattern with
'~\w+(?=\R\p{L}+$)~u'
See the regex demo.
Note:
(\w+)\R\p{L}+$
- matches and captures into Group 1 any Unicode word chars (due to u
flag), then \R
matches any Unicode line break sequence, and then \p{L}+
matches one or more Unicode letters (till the end of string ($
)\R
solves the problem with matching LF or CRLF line endingsu
flag with PHP PCRE/PCRE2 regexps.Upvotes: 1