preg_match unicode解析

时间:2012-04-28 15:57:19

标签: php unicode preg-match

我想匹配一组unicode / UTF-8字符(在这里用黄色标记http://solomon.ie/unicode/),从我的研究中得出这个:

// ensure it's valid unicode / get rid of invalid UTF8 chars
$text = iconv("UTF-8","UTF-8//IGNORE",$text);

// and just allow a basic english...ish.. chars through - no controls, chinese etc
$match_list = "\x{09}\x{0a}\x{0d}\x{20}-\x{7e}"; // basic ascii chars plus CR,LF and TAB 
$match_list .= "\x{a1}-\x{ff}"; // extended latin 1 chars excluding control chars
$match_list .= "\x{20ac}"; // euro symbol

if (preg_match("/[^$match_list]/u", $text) )
    $error_text_array[] = "<b>INVALID UNICODE characters</b>";

测试似乎表明它按预期工作,但作为uniocde的新手,如果有人能发现我忽略的任何漏洞,我将不胜感激。

我可以确认十六进制范围是否匹配unicode代码点而不是实际的十六进制值(即欧元符号的x20ac而不是xe282ac是正确的)?

我可以混合文字字符和十六进制值,如preg_match(“/ [^ 0-9 \ x {20ac}] / u”,$ text)?

谢谢, 凯文

注意,我之前尝试过这个问题,但它已经关闭 - “更适合于codereview.stackexchange.com”,但没有回复,所以希望可以再用更简洁的格式再试一次。

1 个答案:

答案 0 :(得分:2)

我创建了一个包装器来测试你的代码,我认为它可以过滤你期望的字符,但是当你找到无效的UTF-8字符时,你的代码会导致E_NOTICE。所以我认为你应该在iconv行的开头添加@来抑制通知。

对于第二个问题,可以混合文字字符和十六进制值。您也可以自己尝试一下。 :)

<?php
function generatechar($char)
{
    $char = str_pad(dechex($char), 4, '0', STR_PAD_LEFT);
    $unicodeChar = '\u'.$char;
    return json_decode('"'.$unicodeChar.'"');
}
function test($text)
{   
    // ensure it's valid unicode / get rid of invalid UTF8 chars
    @$text = iconv("UTF-8","UTF-8//IGNORE",$text); //Add @ to surpress warning
    // and just allow a basic english...ish.. chars through - no controls, chinese etc
    $match_list = "\x{09}\x{0a}\x{0d}\x{20}-\x{7e}"; // basic ascii chars plus CR,LF and TAB
    $match_list .= "\x{a1}-\x{ff}"; // extended latin 1 chars excluding control chars
    $match_list .= "\x{20ac}"; // euro symbol

    if (preg_match("/[^$match_list]+/u", $text)  )
        return false;

    if(strlen($text) == 0)
        return false; //For testing purpose!
    return true;
}

for($n=0;$n<65536;$n++)
{
    $c = generatechar($n);
    if(test($c))
        echo $n.':'.$c."\n";
}