Php 允许使用外来字符
我有以下PHP正则表达式代码:Php 允许使用外来字符,php,regex,Php,Regex,我有以下PHP正则表达式代码: $input = $_POST['name_field']; if (!preg_match("/^[\pL0-9_.,!\"' ]+$/", $input)) { echo 'error'; } 但是,如果$input包含á、é等字符,则表示错误(即回声错误) 我做错了什么?正如Casimir和Hippolyte所评论的,您需要使用u模式修饰符来支持UTF-8字符: 此修改器启用PCRE的其他功能,即 与Perl不兼容。模式字符串和主题字符串被视为
$input = $_POST['name_field'];
if (!preg_match("/^[\pL0-9_.,!\"' ]+$/", $input)) {
echo 'error';
}
但是,如果$input
包含á
、é
等字符,则表示错误(即回声错误
)
我做错了什么?正如Casimir和Hippolyte所评论的,您需要使用
u
模式修饰符来支持UTF-8字符:
此修改器启用PCRE的其他功能,即
与Perl不兼容。模式字符串和主题字符串被视为
UTF-8
对代码的修改表明,u
pattern修饰符可以根据需要工作:
<?php
// NOTE: array of sample input strings to demonstrate
$inputs = array(
'my_fiancée', // match expected
'über', // match expected
'my_bloody_valentine', // match expected
'"ABC, Easy as 123!"', // match expected
'whocares@whocares.com', // match NOT expected
"'foo'", // match expected
'bar?'); // match NOT expected
foreach($inputs as $input) {
if (!preg_match("/^[\pL0-9_.,!\"' ]+$/u", $input)) {
// ^
echo "\"$input\" => error\r\n"; // FORNOW: to explicitly note non-matches
//echo 'error';
} else { // FORNOW: else to explicitly indicate matches
echo "\"$input\" => all good\r\n";
}
}
?>
您也可以。添加u修改器。更有效的方法是否定字符类:
if(preg\u match(“/[^\pL0-9\u.”,!\“']/u”,$input))
你应该把它作为一个答案添加进去,这样我就可以把它标记为已解决了。:)我立即得到了相同的评论,关于u
模式修饰符:所以我继续添加它作为相应的答案。检查你对PHP是由来自格陵兰岛的人编写的。
"my_fiancée" => all good
"über" => all good
"my_bloody_valentine" => all good
""ABC, Easy as 123!"" => all good
"whocares@whocares.com" => error
"'foo'" => all good
"bar?" => error