'Regex not working in PHP code but working fine in the sandbox

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?



Solution 1:[1]

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 endings
  • When using Unicode property classes and dealing with Unicode strings, remember to use u flag with PHP PCRE/PCRE2 regexps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew