Home > Software engineering >  PHP Regex - optional Unicode UTF-8 character (Ø?) is not working
PHP Regex - optional Unicode UTF-8 character (Ø?) is not working

Time:08-06

I have string where it contains Ø character but not always:

$pattern = '/Ø?\d [a-z-] Ø?\d /i';
if (preg_match($pattern, 'Ø66-SX-76', $matched)) {
    print_r($matched);
}
if (preg_match($pattern, '58-SX-72', $matched)) {
    print_r($matched);
}
if (preg_match($pattern, 'Ø66-SX-Ø76', $matched)) {
    //only this one matches
    print_r($matched);
}

These are a basic example of the string I am processing.

Can somebody explain why the first 2 cases are not matching?

When I try on regexpal.com this pattern is working for all case, but on PHP it is not working

CodePudding user response:

You can instruct the regex engine to treat the input string as utf-8. Add the u modifier at the end:

$pattern = '/Ø?\d [a-z-] Ø?\d /iu';

CodePudding user response:

Thanks to @Joey, adding wrapping Ø in parantheses worked:

$pattern = '/(Ø)?\d [a-z-] (Ø)?\d /i';
  • Related