2012-04-28 25 views
1

我想匹配的子集的Unicode/UTF-8字符的,(黄色标记这里http://solomon.ie/unicode/),从我的研究,我想出了这一点:的preg_match的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”,$文字)?

感谢, 凯文

注意,我尝试过这个问题,但它被关闭了 - “更适合codereview.stackexchange.com”,但没有任何反应,以便希望这是确定在更再试一次更简洁的格式。

回答

2

我创建了一个包装,以测试你的代码,我认为这是在过滤你需要的字符安全,但您的代码将导致E_NOTICE的时候才发现无效的UTF-8字符。所以我认为你应该在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"; 
} 
+0

chalet16 - 许多感谢。回到办公室后,我会玩你的测试代码。我已经混合字符按我的例子,它似乎好的工作,但只是检查成为你的努力,凯文 – KevInSol 2012-04-28 17:23:57

+0

喜肯定:)再次非常感谢,我得试试这个,现在,它的工作主要是作为预期除了我似乎将u + d800改回u + dfff。我没有看到我要去哪里错了。另外我注意到你添加了+ metachar到我的正则表达式 - 是否需要当匹配不在列表中的蚂蚁char? – KevInSol 2012-04-30 11:40:48

+0

我刚才看到u + d800到u + dfff是代理对 - 但是这似乎在UTF-16中使用,而不是8? iconv应该剥离它们吗? – KevInSol 2012-04-30 11:54:04