preg_match is matching two characters when it shou

2019-08-28 22:00发布

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

In this example, the function returns "¿h", but "¿" was expected... I can't figure out the problem...

1条回答
叼着烟拽天下
2楼-- · 2019-08-28 22:34

Try to use the flag "u" (as documented on this page) in your regex: /[a-zäáàëéèíìöóòúùñç]/u

And prefer saving your files in UTF-8 rather than using mb_convert_encoding on static strings.

查看更多
登录 后发表回答