preg_match匹配两个字符时,应该只匹配一个 [英] preg_match is matching two characters when it should only match one
问题描述
我正在尝试从字符串中提取特殊字符(从预定义的模式中),但是当该字符串以反向问号开头时,matches将返回前两个字符,包括不是特殊字符。例如:
I'm trying to extract the special characters (out of a predefined pattern) from a string, but when that string begins with an inverted question mark, "matches" returns first two characters, including a not special one. Eg.:
$string = '¿hola?';
$string2 = mb_convert_encoding($string, 'UTF-8');
$regex = mb_convert_encoding('/[a-zäáàëéèíìöóòúùñç]/', 'UTF-8');
if(preg_match($regex, $string2, $matches, PREG_OFFSET_CAPTURE))
{
//--> We pick the special characters into "$resultado1":
$resultado1 = mb_substr($string, 0, $matches[0][1],'UTF-8');
return $resultado1;
}
在这个例子中,函数返回¿h,但¿预期...我无法弄清楚问题...
In this example, the function returns "¿h", but "¿" was expected... I can't figure out the problem...
推荐答案
尝试使用标志u(正如您所使用的正则表达式中的此页面所述): / [a-zäáàëéèíìöóòúùñç] / u
Try to use the flag "u" (as documented on this page) in your regex: /[a-zäáàëéèíìöóòúùñç]/u
更喜欢将文件保存在UTF-8中,而不是在静态上使用mb_convert_encoding字符串。
And prefer saving your files in UTF-8 rather than using mb_convert_encoding on static strings.
这篇关于preg_match匹配两个字符时,应该只匹配一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!