简体   繁体   English

PHP 正则表达式 - 可选 Unicode UTF-8 字符(Ø?)不起作用

[英]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当我尝试使用 regexpal.com 时,此模式适用于所有情况,但在 PHP 上它不起作用

You can instruct the regex engine to treat the input string as utf-8.您可以指示正则表达式引擎将输入字符串视为 utf-8。 Add the u modifier at the end:在末尾添加u修饰符:

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

Thanks to @Joey, adding wrapping Ø in parantheses worked:感谢@Joey,在括号中添加包装 Ø 起作用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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