utf-8的preg_match规则

时间:2013-01-24 22:19:35

标签: php utf-8 preg-match

我必须为full_name字段使用什么pregmach规则?
我希望用户只输入字符而不是html或php代码值和3到11个字符之间的空格
我可以用:

<?php
if (preg_match("%^[A-Za-z0-9-_]{3,10}$%", $_REQUEST['usr'])) {
//do something like 
mysql_query('insert into user(name) values(this field)');
//damn what is this for: It does not meet our quality standards.!!!
//i must insert more code? i dont have ! let me go !
}
else{
//do something else!
die('get out !:D');
}
?>

但是此用户无法输入UTF-8字符,例如“مسیحارسطوئی”
那么我必须为UTF-8使用什么preg_match规则?
或者我可以使用像preg_match这样的其他代码吗? 我想要用户只能插入不是&lt;&gt; {} []或$%^&amp; *
的字符 3至10个字符! 感谢

3 个答案:

答案 0 :(得分:2)

使用u修饰符,如下所示:

preg_match('/pattern_with_unicode_symbols/u');

此修饰符打开与Perl不兼容的PCRE的其他功能。模式字符串被视为UTF-8。

并使用“\ x {2460}”语法来定义utf-8字符

答案 1 :(得分:2)

这将给出“0”,cos مسیح ارسطوئی不包含3-10个字符;

$x = preg_match('~^([\pL]{3,10})$~u', 'مسیح ارسطوئی');
echo $x ? 1 : 0;

但是这会给你的结果带来结果;

preg_match('~([\pL]+)~u', 'مسیح ارسطوئی', $m);
print_r($m);

Array
(
    [0] => مسیح
    [1] => مسیح
)

在此处查看更多详情:PHP: Unicode character properties

答案 2 :(得分:0)

preg_match_all('/#(\pL*)/u', 'this is #مثال text', $matches);
print_r($matches);

'u','\ pL':字符串被视为UTF-8。