简体   繁体   中英

PHP Regex - optional Unicode UTF-8 character (Ø?) is not working

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

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';

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM